Weeknumberology in .NET

Thursday, the third day ;-).

Tagged with: csharp, programming

Published on

I’m currently writing a little program in C# (.NET 9) that needs to do some calculations with weeks. Specifically ISO weeks which start on Monday and the first week of a year is defined as the first week that contains the first Thursday of a year. I started to write some code that gets me the first day of the first week of the year when I stumbled over the System.Globalization.ISOWeek class. This humble static class contains six methods that cover the common things one may want to do with week numbers.

GetWeekOfYear(DateTime) returns the week number of a date. For example, GetWeekOfYear(new DateTime(2024, 12, 15)) will return 50.

The method GetWeeksInYear(Int32) returns the number of weeks in a given year. For 2024 this method returns 52.

GetYear(DateTime) may surprise you but according to the ISO week numbering system a day in a year may not be in that year if its week isn’t part of the year. Namely, the 1st January 2023 is actually part of the 52 week of 2022. When you pass it to GetYear(DateTime) you get 2022.

In order to get the start and end date of a year when working with week the methods GetYearStart(Int32) and GetYearEnd(Int32) can be used. For instance, the start of the year 2023 is the 2nd January 2023 and the end of 2022 is the 1st January 2023.

Last but not least there is ToDateTime(Int32, Int32, DayOfWeek) which will calculate the date of a weekday of a week in a year. When called like this ToDateTime(2024, 50, DayOfWeek.Sunday) the method will return the 15th December 2024.

I was relieved that I found this small but very helpful class. This once again demonstrates the vast collection of things that come with the .NET standard library that make our lives as developers easier.