How do I find the start of the week (both Sunday and Monday) knowing just the current time in C#?
Something like:
DateTime.Now.StartWeek(Monday);
How do I find the start of the week (both Sunday and Monday) knowing just the current time in C#?
Something like:
DateTime.Now.StartWeek(Monday);
The following method should return the DateTime that you want. Pass in true for Sunday being the first day of the week, false for Monday:
This will return both the beginning of the week and the end of the week dates:
I have posted the complete code for calculating the begin/end of week, month, quarter and year on my blog ZamirsBlog
You could use the excellent Umbrella library:
However, they do seem to have stored Monday as the first day of the week (see the property
nVentive.Umbrella.Extensions.Calendar.DefaultDateTimeCalendarExtensions.WeekBeginsOn
), so that previous localized solution is a bit better. Unfortunate.Edit: looking closer at the question, it looks like Umbrella might actually work for that too:
Although it's worth noting that if you ask for the previous Monday on a Monday, it'll give you seven days back. But this is also true if you use
BeginningOfWeek
, which seems like a bug :(.This may be a bit of a hack, but you can cast the .DayOfWeek property to an int (it's an enum and since its not had its underlying data type changed it defaults to int) and use that to determine the previous start of the week.
It appears the week specified in the DayOfWeek enum starts on Sunday, so if we subtract 1 from this value that'll be equal to how many days the Monday is before the current date. We also need to map the Sunday (0) to equal 7 so given 1 - 7 = -6 the Sunday will map to the previous Monday:-
The code for the previous Sunday is simpler as we don't have to make this adjustment:-
We like one-liners : Get the difference between the current culture's first day of week and the current day then subtract the number of days from the current day