Week of Year C# Datetime

坚强是说给别人听的谎言 提交于 2019-12-04 03:11:08

问题


I have following code to get the weeknumber of the year given in the DateTime object Time

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

Now i give the function the date 1/1/2012 wich should return week 1 , but hes returning week 52. And i can't seem to figure out why. Anyone have an idea why ?


回答1:


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




回答2:


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.




回答3:


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.




回答4:


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 );



回答5:


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.




回答6:


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.



来源:https://stackoverflow.com/questions/10102714/week-of-year-c-sharp-datetime

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