CultureInfo
First, we need the CultureInfo to use. We can get the current culture, or a specific one:
// Get the culture used by the current thread
public static readonly CultureInfo Culture = CultureInfo.CurrentCulture;
// Get a specific culture
public static readonly CultureInfo Culture = new CultureInfo("el-GR");
Method
Then this short method will return the first day of the week.
public static DateTime GetFirstDayOfWeek(DateTime date)
{
return date.AddDays(-((date.DayOfWeek - Culture.DateTimeFormat.FirstDayOfWeek + 7) % 7)).Date;
}
Test tables
DoW: Day of Week
DoW | First DoW | AddDays | Resulting DoW |
---|---|---|---|
0 | 0 | -(0 - 0 + 7) % 7 = 0 | 0 + 0 = 0 |
1 | 0 | -(1 - 0 + 7) % 7 = -1 | 1 - 1 = 0 |
2 | 0 | -(2 - 0 + 7) % 7 = -2 | 2 - 2 = 0 |
3 | 0 | -(3 - 0 + 7) % 7 = -3 | 3 - 3 = 0 |
4 | 0 | -(4 - 0 + 7) % 7 = -4 | 4 - 4 = 0 |
5 | 0 | -(5 - 0 + 7) % 7 = -5 | 5 - 5 = 0 |
6 | 0 | -(6 - 0 + 7) % 7 = -6 | 6 - 6 = 0 |
DoW | First DoW | AddDays | Resulting DoW |
---|---|---|---|
0 | 1 | -(0 - 1 + 7) % 7 = -6 | 0 - 6 = 1 |
1 | 1 | -(1 - 1 + 7) % 7 = 0 | 1 - 0 = 1 |
2 | 1 | -(2 - 1 + 7) % 7 = -1 | 2 - 1 = 1 |
3 | 1 | -(3 - 1 + 7) % 7 = -2 | 3 - 2 = 1 |
4 | 1 | -(4 - 1 + 7) % 7 = -3 | 4 - 3 = 1 |
5 | 1 | -(5 - 1 + 7) % 7 = -4 | 5 - 4 = 1 |
6 | 1 | -(6 - 1 + 7) % 7 = -5 | 6 - 5 = 1 |