Week of Year C# Datetime

不打扰是莪最后的温柔 提交于 2019-12-01 16:13:46
KingCronus

The algorithm is doing exactly what you have instructed it to do. You have the CalanderWeekRule set to FirstFourDayWeek. The 1st of January 2012 was not part of the first four day week, so you have instructed the calander to start counting from January 2nd.

Calculate date from week number

Qmash
public static int WeeksInYear(DateTime date)
{
    GregorianCalendar cal = new GregorianCalendar(GregorianCalendarTypes.Localized);
    return cal.GetWeekOfYear(date, CalendarWeekRule.FirstDay, DayOfWeek.Monday);

i think if change CalendarWeekRule.FirstFourDayWeek to CalendarWeekRule.FirstDay then this will work fine.

i change this then its working fine.

The weeknumber was correctly calculated. You should have a read on how weeknumbers are actually calculated/counted (Wikipedia?!).

Attention: The built-in calculation of week-number-calculation is buggy. Microsoft describes the problem in the KnowledgeBase-Article 200299. It has problems with ISO-8601.

You can use the class Week of the Time Period Library for .NET which supports supports the ISO 8601 week numbering:

TimeCalendar calendar = new TimeCalendar(
    new TimeCalendarConfig { YearWeekType = YearWeekType.Iso8601 } );
Week week = new Week( new DateTime( 2012, 01, 01 ), calendar );
Console.WriteLine( "week #: ", week.WeekOfYear );

I assume that because 1/1/2012 was a Sunday and GetWeekOfYear says it returns the week which includes the date, it's returning the last week of 2011 rather than the first week of 2012.

Have a look at the CalendarRule for clarification.

1/1/2012 it was sunday. I believe that's why you get 52, because it was last day of the last year week. For the 2nd of january you should get the right result.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!