我搜索了很多并找到了很多解决方案,但没有一个能给我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)