13,091,548 members (69,288 online)
Tip/Trick
alternative version

#### Stats

17.9K views
8 bookmarked
Posted 10 Dec 2009

# Week numbers according to ISO8601

, 8 Mar 2010
 Rate this:
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...
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 preceeding 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:

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

int nIndex = -1;

if (dt.DayOfWeek > DayOfWeek.Thursday || dt.DayOfWeek == DayOfWeek.Sunday)
nIndex = 1;

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

// 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.

## Share

 Retired United Kingdom
I was a Software Support Engineer for many years using various legacy enterprise systems before learning UNIX and Windows programming - the latter largely in my own time. In my last few years of employment I spent more time in actual development.

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

One day I hope to become a real programmer.