How can I calculate/find the week-number of a given date?

后端 未结 7 1974
耶瑟儿~
耶瑟儿~ 2020-12-01 03:35

How can I calculate/find the week-number of a given date?

相关标签:
7条回答
  • 2020-12-01 04:36

    var cultureInfo = CultureInfo.CurrentCulture; var calendar = cultureInfo.Calendar;

            var calendarWeekRule = cultureInfo.DateTimeFormat.CalendarWeekRule;
            var firstDayOfWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek;
            var lastDayOfWeek = cultureInfo.LCID == 1033 //En-us
                ? DayOfWeek.Saturday
                : DayOfWeek.Sunday;
    
            var lastDayOfYear = new DateTime(date.Year, 12, 31);
    
             //Check if this is the last week in the year and it doesn`t occupy the whole week
            var weekNumber = calendar.GetWeekOfYear(date, calendarWeekRule, firstDayOfWeek);
            return weekNumber == 53 && lastDayOfYear.DayOfWeek != lastDayOfWeek 
                   ? 1 
                   : weekNumber;
    

    It works well both for US and Russian cultures. ISO 8601 also will be correct, `cause Russian week starts at Monday.

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