Home > Backend Development > C++ > How to Correctly Determine the Week Number of a Given Date?

How to Correctly Determine the Week Number of a Given Date?

Mary-Kate Olsen
Release: 2025-01-25 12:21:11
Original
235 people have browsed it

How to Correctly Determine the Week Number of a Given Date?

Accurately calculate the weekly number of the given date

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#

  • python
// 假设一周从星期一开始
// 第 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);
}
Copy after login
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
Copy after login
    By comparing the ISO 8601 standard, these solutions can accurately return to the first week on December 31, 2012, thereby ensuring the correct week of any given date.

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template