Calculate previous week's start and end date
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.
Solution 1:
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.
Solution 2:
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.
Solution 3:
using Fluent DateTime https://github.com/FluentDateTime/FluentDateTime
var dateTime = 1.Weeks().Ago();
var monday = dateTime.Previous(DayOfWeek.Sunday);
var sunday = dateTime.Next(DayOfWeek.Sunday);
Solution 4:
Using DayOfWeek would be a way of achieving this:
DateTime date = DateTime.Now.AddDays(-7);
while (date.DayOfWeek != DayOfWeek.Monday)
{
date = date.AddDays(-1);
}
DateTime startDate = date;
DateTime endDate = date.AddDays(7);