21 May 2024

Getting the first day in a week with C#

For my Blazor Calendar component, I ran into a small problem to determine the first day of the week. It’s not new and the web is full of solutions that in the end… well, they are only based on Saturday or Sunday. Except that there are countries like Afghanistan, Iran and Somalia where the first day of the week is Saturday.

Saturday? Sunday ? Monday ? Friday!

In fact it’s not that simple because it should be noted that it can vary according to the culture and traditions of each region. Unless I go to each country to investigate, the web tells me everything and its opposite. If I look at Wikipedia, I find this map:

First Day of Week World Map

And obviously in Maldives it is a Friday

source : https://commons.wikimedia.org/wiki/File_talk:First_Day_of_Week_World_Map.svg

ChatGPT, Stack Overflow, help!

Well, there are no good answers for me. And the following code using simply DateTime.FirstDayOfWeek, finally returns me Sunday.


My need is to give him the day of the month and he returns the number of the first day of the week. Previously I will have specified in my code the Culture.

I then start on the day numbers like DayOfWeek with 0 for Sunday, 1 for Monday and so on.


And now everything is fine!

All is well? Well ok, I didn’t manage the Maldives. If I have a maldivian as a user, I have an improvement to make

Leave a Reply