我搜索了很多并找到了很多解决方案,但没有一个能给我2012-12-31的正确周数.甚至MSDN(链接)上的示例都失败了.
2012-12-31是星期一,因此它应该是第1周,但我尝试的每种方法都给了我53.以下是我尝试过的一些方法:
来自MDSN图书馆:
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
Calendar cal = dfi.Calendar;
return cal.GetWeekOfYear(date, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);
Run Code Online (Sandbox Code Playgroud)
解决方案2:
return new GregorianCalendar(GregorianCalendarTypes.Localized).GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
Run Code Online (Sandbox Code Playgroud)
解决方案3:
CultureInfo ciCurr = CultureInfo.CurrentCulture;
int weekNum = ciCurr.Calendar.GetWeekOfYear(dtPassed, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
return weekNum;
Run Code Online (Sandbox Code Playgroud)
更新
当日期为2012-12-31时,以下方法实际返回1.换句话说,我的问题是我的方法不符合ISO-8601标准.
// This presumes that weeks start with Monday.
// Week 1 is the 1st week of the year with a Thursday in it.
public static int GetIso8601WeekOfYear(DateTime time)
{
// Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
// be …Run Code Online (Sandbox Code Playgroud) 我正在计算日期的周数,但是在System.Globalization.Calendar2007年和2012年的12月31日(其他年份)中,它将返回奇数结果.
Calendar calendar = CultureInfo.InvariantCulture.Calendar;
var date = new DateTime(2007, 12, 29);
for (int i = 0; i < 5; i++)
{
int w = calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
Console.WriteLine("{0}\t{1}", date.ToString("dd.MM.yyyy"), w);
date = date.AddDays(1);
}
Run Code Online (Sandbox Code Playgroud)
结果
29.12.2007 52
30.12.2007 52
31.12.2007 53 <--
01.01.2008 1
02.01.2008 1
29.12.2012 52
30.12.2012 52
31.12.2012 53 <--
01.01.2013 1
02.01.2013 1
Run Code Online (Sandbox Code Playgroud)
据我了解,2007年和2012年不应该有53周,但是应该在第1周包括这些日子.有没有办法改变这种行为Calendar?