Home >Backend Development >C++ >How to Get the Correct ISO-8601 Week Number for Any Given Date?

How to Get the Correct ISO-8601 Week Number for Any Given Date?

DDD
DDDOriginal
2025-01-25 12:16:10570browse

How to Get the Correct ISO-8601 Week Number for Any Given Date?

Get the correct week number for a given date according to ISO-8601 standard

Challenge:

Determining the correct number of weeks for a given date can be tricky, especially when dealing with end-of-year dates. Existing .NET methods often fail to comply with the ISO-8601 standard and assign incorrect week numbers to some dates.

Wrong week number:

For example, the .NET approach might mark December 31, 2012 as week 53, but this is incorrect according to the ISO-8601 standard. This difference stems from the fact that .NET allows weeks to span years, while ISO-8601 does not.

Solution:

To get the correct ISO-8601 week number, use the following function:

<code class="language-csharp">// 假设周从星期一开始。
// 第 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);
    }
    else if (day > DayOfWeek.Wednesday)
    {
        time = time.AddDays(10 - (int)day);
    }
    return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}</code>

Principle description:

This function adjusts the date when it falls on a Monday, Tuesday, or Wednesday, ensuring that it represents the same week as the upcoming Thursday, Friday, or Saturday. This method complies with the ISO-8601 standard, which defines week 1 as the first week that contains a Thursday.

Example:

For the December 31, 2012 date mentioned in the challenge, this function returns 1, which is the correct week number according to the ISO-8601 standard.

The above is the detailed content of How to Get the Correct ISO-8601 Week Number for Any Given Date?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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