Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / Java
Tip/Trick

Week Numbers according to ISO8601

Rate me:
Please Sign up or sign in to vote.
4.80/5 (16 votes)
8 Mar 2010CPOL1 min read 25K   8  
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)


Written By
Retired
United Kingdom United Kingdom
I was a Software Engineer for 40+ years starting with mainframes, and moving down in scale through midi, UNIX and Windows PCs. I started as an operator in the 1960s, learning assembler programming, before switching to development and graduating to COBOL, Fortran and PLUS (a proprietary language for Univac systems). Later years were a mix of software support and development, using mainly C, C++ and Java on UNIX and Windows systems.

Since retiring I have been learning some of the newer (to me) technologies (C#, .NET, WPF, LINQ, SQL, Python ...) that I never used in my professional life, and am actually able to understand some of them.

I still hope one day to become a real programmer.

Comments and Discussions

 
-- There are no messages in this forum --