获取或将一年中的一周转换为 ISO 周 [英] Get or convert Week of year to ISO week

查看:35
本文介绍了获取或将一年中的一周转换为 ISO 周的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试获取一年中的周数时,我尝试了以下方法:

While trying to get the number of weeks in a year I tried this:

maxWeek = calendar.GetWeekOfYear(New Date(t_year, 12, 31), 
          CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)

这不符合我的目的,但我注意到一些奇怪的事情.对于 2014-12-31,它返回 53,对于 2015-01-01,它返回 1.对于 2015-01-05,它返回 2.这意味着第 53 周和第 1 周小于 7 天!

Which didn't work well for my purpouse, but I noticed something weird. For 2014-12-31 it returned 53 and for 2015-01-01 it returned 1. For 2015-01-05 it returned 2. That means that the weeks 53 and 1 are smaller then 7 days!

我需要结果符合ISO 周.我在网上找不到任何遵循相同逻辑的日历示例.它们都显示了从 2014-12-29 到 2015-01-04 的第 1 周.

I need the result to be ISO Week compliant. I couldn't find online any examples of calendars following this same logic. Them all show the week 1 as from 2014-12-29 to 2015-01-04.

推荐答案

您的原始帖子没有提到您正在寻找 ISO 周,这可能使您不清楚想要什么.

Your original post does not mention you are looking for ISO week, which may have made what you want unclear.

使用 FirstFourDayWeekDayOfWeek.Monday 的 NET GetWeekOfYear 几乎就像一个 ISO 周.不同之处在于 ISO 周始终为 7 天.请记住,ISO 日期不仅仅是一种不同的格式,而是一种不同的日历,带有自己的术语(如闰周).另一方面,您的默认 NET 日历是 Gregorian.

The NET GetWeekOfYear using FirstFourDayWeek and DayOfWeek.Monday is almost like an ISO Week. The difference is that an ISO Week is always seven days. Keep in mind that an ISO Date is not just a different format, but a different calendar complete with its own terms (like leap week). Your default NET calandar on the other hand is Gregorian.

将 NET WOY 调整为 ISO 周并不难:

It is not hard to tweak a NET WOY to an ISO Week:

Public Shared Function GetISOWeekOfYear(dt As DateTime) As Integer
    Dim cal As Calendar = CultureInfo.InvariantCulture.Calendar
    Dim d As DayOfWeek = cal.GetDayOfWeek(dt)

    If (d >= DayOfWeek.Monday) AndAlso (d <= DayOfWeek.Wednesday) Then
        dt = dt.AddDays(3)
    End If

    Return cal.GetWeekOfYear(dt, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)

End Function

12/31/xxxx 的简单测试器:

Simple tester for 12/31/xxxx:

For n As Integer = 1990 To 2016
    Console.WriteLine("{0}: week:{1}", n.ToString,
                      GetISOWeekOfYear(New DateTime(n, 12, 31)).ToString)
Next

只输出最后几个:

2005 年:周:52
2006 年:周:52
2007 年:周:1
2008 年:周:1
2009 年:周:53
2010 年:周:52
2011 年:周:52
2012 年:周:1
2013 年:周:1
2014 年:周:1
2015 年:周:53
2016 年:周:52

2005: week:52
2006: week:52
2007: week:1
2008: week:1
2009: week:53
2010: week:52
2011: week:52
2012: week:1
2013: week:1
2014: week:1
2015: week:53
2016: week:52

这篇关于获取或将一年中的一周转换为 ISO 周的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆