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

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

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

7条回答
  •  攒了一身酷
    2020-12-01 04:28

    If you want the ISO 8601 Week Number, in which weeks start with a monday, all weeks are seven days, and week 1 is the week containing the first thursday of the year, this may be a solution.

    Since there doesn't seem to be a .Net-culture that yields the correct ISO-8601 week number, I'd rater bypass the built in week determination alltogether, and do the calculation manually, instead of atempting to correct a partially correct result.

    What I ended up with is the following extension method:

    public static int GetIso8601WeekNumber(this DateTime date)
    {    var thursday = date.AddDays(3 - ((int)date.DayOfWeek + 6) % 7);
         return 1 + (thursday.DayOfYear - 1) / 7;
    }
    

    First of all, ((int)date.DayOfWeek + 6) % 7) determines the weekday number, 0=monday, 6=sunday.

    date.AddDays(-((int)date.DayOfWeek + 6) % 7) determines the date of the monday preceiding the requested week number.

    Three days later is the target thursday, which determines what year the week is in.

    If you divide the (zero based) day-number within the year by seven (round down), you get the (zero based) week number in the year.

    In c#, integer calculation results are round down implicitly.

提交回复
热议问题