The correct number of the given date may be a tricky task, especially when it spans two years on the weekend. This is obvious when trying to find the weekly number of December 31, 2012. Many standard methods return incorrect values 53 instead of 1.
This difference lies in the difference between the ISO8601 weekly number and the .NET weekly number. Although the .NET allowed the week to span the year, the ISO standard was not allowed.
ISO 8601 Week number
According to the ISO 8601, the first week of the year is the week of the first Thursday that year. This means that December 31, 2012 belongs to the first week of 2013.
Solution in different programming languages
C#
// 假设一周从星期一开始 // 第 1 周是当年包含星期四的第一周 public static int GetIso8601WeekOfYear(DateTime time) { // 通过移动到同一周的星期四、星期五或星期六来处理星期一、星期二或星期三 DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time); if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday) { time = time.AddDays(3 - (int)day); } // 现在,我们知道这一周的星期四在这一周内,我们可以计算周数 return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); }
import datetime def get_iso_week_number(date): """ 获取日期的 ISO 8601 周数。 :param date: 要获取周数的日期。 :type date: datetime.datetime :return: ISO 8601 周数。 :rtype: int """ year, week, _ = date.isocalendar() return week
The above is the detailed content of How to Correctly Determine the Week Number of a Given Date?. For more information, please follow other related articles on the PHP Chinese website!