根据官方(格里高利)日历,2008年12月29日的周数为1,因为在第52周的最后一天(即28/12)之后,该年剩下三天或更少的天数.有点奇怪,但没关系,规则是规则.
因此,根据这个日历,我们有2008/2009年的这些边界值
28/12是第52周
29/12是第1周
1/1是第1周
8/1是第2周
C#提供了一个GregorianCalendar类,它有一个函数GetWeekOfYear(date, rule, firstDayOfWeek)
.
该参数rule
是一个包含3个可能值的枚举:FirstDay, FirstFourWeekDay, FirstFullWeek
.根据我的理解,我应该FirstFourWeekDay
遵守规则,但我尝试了所有这些以防万一.
最后一个参数通知哪个工作日应该被视为一周的第一天,根据该日历,它是星期一,所以它是星期一.
所以我启动了一个快速而肮脏的控制台应用程序来测试这个:
using System; using System.Globalization; namespace CalendarTest { class Program { static void Main(string[] args) { var cal = new GregorianCalendar(); var firstWeekDay = DayOfWeek.Monday; var twentyEighth = new DateTime(2008, 12, 28); var twentyNinth = new DateTime(2008, 12, 29); var firstJan = new DateTime(2009, 1, 1); var eightJan = new DateTime(2009, 1, 8); PrintWeekDays(cal, twentyEighth, firstWeekDay); PrintWeekDays(cal, twentyNinth, firstWeekDay); PrintWeekDays(cal, firstJan, firstWeekDay); PrintWeekDays(cal, eightJan, firstWeekDay); Console.ReadKey(); } private static void PrintWeekDays(Calendar cal, DateTime dt, DayOfWeek firstWeekDay) { Console.WriteLine("Testing for " + dt.ToShortDateString()); Console.WriteLine("--------------------------------------------"); Console.Write(CalendarWeekRule.FirstDay.ToString() + "\t\t"); Console.WriteLine(cal.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, firstWeekDay)); Console.Write(CalendarWeekRule.FirstFourDayWeek.ToString() + "\t"); Console.WriteLine(cal.GetWeekOfYear(dt, CalendarWeekRule.FirstFourDayWeek, firstWeekDay)); Console.Write(CalendarWeekRule.FirstFullWeek.ToString() + "\t\t"); Console.WriteLine(cal.GetWeekOfYear(dt, CalendarWeekRule.FirstFullWeek, firstWeekDay)); Console.WriteLine("--------------------------------------------"); } } }
......这就是我得到的
Testing for 28.12.2008 -------------------------------------------- FirstDay 52 FirstFourDayWeek 52 FirstFullWeek 51 -------------------------------------------- Testing for 29.12.2008 -------------------------------------------- FirstDay 53 FirstFourDayWeek 53 FirstFullWeek 52 -------------------------------------------- Testing for 01.01.2009 -------------------------------------------- FirstDay 1 FirstFourDayWeek 1 FirstFullWeek 52 -------------------------------------------- Testing for 08.01.2009 -------------------------------------------- FirstDay 2 FirstFourDayWeek 2 FirstFullWeek 1 --------------------------------------------
因此,正如我们所看到的,上面的组合都没有与官方日历相匹配(如果你匆忙,只看到29/12从未得到第1周).
我在这里弄错了什么?也许有些东西明显让我失踪?(这是比利时的星期五和晚上的工作时间,请耐心等待;))
编辑:也许我应该解释一下:我需要的是一个适用于任何年份的函数,返回与我链接的格里高利历相同的结果.因此,2008年没有特别的解决方法.
此文章看起来更深的问题和可能的解决方法.问题的中心是.NET日历实现似乎没有忠实地实现ISO标准