What is the best way to calculate the previous week's start and end date in C#? I.e. today 18 March would result in 9 March (Monday last week) and 15 March (Sunday last week).
I have seen this done with DayOfWeek and a switch statement to work out an offset but was wondering whether there is a more elegant way.
You can skip the while loop and use
DateTime mondayOfLastWeek = date.AddDays( -(int)date.DayOfWeek - 6 );
This assumes you're using Monday as the first day of the week.
DayOfWeek weekStart = DayOfWeek.Monday; // or Sunday, or whenever DateTime startingDate = DateTime.Today; while(startingDate.DayOfWeek != weekStart) startingDate = startingDate.AddDays(-1); DateTime previousWeekStart = startingDate.AddDays(-7); DateTime previousWeekEnd = startingDate.AddDays(-1);
Read: Backtrack one day at a time until we're at the start of this week, and then subtract seven to get to the start of last week.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With