Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Java

Week Numbers according to ISO8601

4.80/5 (16 votes)
8 Mar 2010CPOL1 min read 25.6K  
Week numbers according to ISO8601

A question arose recently in the C# forum about computing a date or day of the week based on a particular week number in the year.

The problem appeared quite simple at first, just add (number of weeks * 7) to 1st January and adjust as necessary. However, as a number of posters pointed out, the official first week of the year does not always start on 1st January, but on the Monday preceding the first Thursday of the year, as defined in ISO 8601[^]. This value is not offered as part of the DateTime structure, so I created the following code snippet to find the first ISO8601 week in any year.

The calculation is relatively simple, complicated only by the fact that most weekday enumerations set Sunday as the first, rather than the last day of the week. Starting with the 1st of January, the date needs to be adjusted forwards or backwards to the Monday preceding the first Thursday and this can be achieved using the code below:

C#
DateTime DtCalc(int nYear)
{
    DateTime dt = new DateTime(nYear, 1, 1);

    // adjust backwards by default
    int nIndex = -1;

    // if Fri/Sat/Sun adjust forwards
    if (dt.DayOfWeek > DayOfWeek.Thursday || dt.DayOfWeek == DayOfWeek.Sunday)
        nIndex = 1;

    // adjust the date until day is Monday
    while (dt.DayOfWeek != DayOfWeek.Monday)
        dt = dt.AddDays(nIndex);

    // return the normalised date
    return dt;
}

I leave the creation of the C++, VB, Java and COBOL versions as exercises for the reader.

Luc Pattyn[^] has provided a neat alternative method (see below) for calculating the first Thursday, for which he gets a 5.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)