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

How to Accurately Determine the Week Number of a Date?

Susan Sarandon
Susan SarandonOriginal
2025-01-25 12:12:09742browse

How to Accurately Determine the Week Number of a Date?

Precisely Calculating the Week Number of a Date

Calculating a date's week number is a frequent programming task, but surprisingly complex. Consider 2012-12-31: many methods incorrectly return 53, while intuitively, it should be week 1.

The Problem: Calendar Variations

The core issue lies in calendar inconsistencies. Standard .NET calendars allow weeks to cross year boundaries, unlike the ISO 8601 standard, which keeps weeks within a single year.

The ISO 8601 Solution

To ensure accuracy, using the ISO 8601 standard is essential. The following GetIso8601WeekOfYear method, compliant with this standard, correctly identifies 2012-12-31 as week 1.

<code class="language-csharp">public static int GetIso8601WeekOfYear(DateTime time)
{
    DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
    if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
    {
        time = time.AddDays(3);
    }
    return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}</code>

This method guarantees week number calculation according to ISO 8601, offering consistent and logical results.

The above is the detailed content of How to Accurately Determine the Week Number of a 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