Week of Year C# Datetime

后端 未结 6 933
情深已故
情深已故 2020-12-20 15:37

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

    public static int WeeksInYear(DateTime date)
    {
        Grego         


        
相关标签:
6条回答
  • 2020-12-20 15:49

    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.

    0 讨论(0)
  • 2020-12-20 15:56

    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

    0 讨论(0)
  • 2020-12-20 16:00

    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.

    0 讨论(0)
  • 2020-12-20 16:02

    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.

    0 讨论(0)
  • 2020-12-20 16:08

    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 );
    
    0 讨论(0)
  • 2020-12-20 16:11
    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 changed this then its working fine.

    0 讨论(0)
提交回复
热议问题