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
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;
while (dt.DayOfWeek != DayOfWeek.Monday)
dt = dt.AddDays(nIndex);
I leave the creation of the C++, VB, Java and COBOL versions as exercises for the reader.
] has provided a neat alternative method (see below) for calculating the first Thursday, for which he gets a 5.