Calculate previous week's start and end date

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.


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);

Tags:

C#