Calculate previous week's start and end date

Viewed 57281

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.

7 Answers

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

Current accepted answer will fail for Sundays by giving the Monday of the current week instead of last weeks Monday. (code with unit tests output)

DateTime mondayOfLastWeek = date.AddDays( -(int)date.DayOfWeek - 6 );
//Failed to get start of last-week from date-time: 2020-03-01T00:00:00.0000000Z
//  Expected: 2020-02-17 00:00:00.000
//  But was:  2020-02-24 00:00:00.000

The following bit of code addresses this issue:

var dayOfWeek = (int) date.DayOfWeek - 1;
if (dayOfWeek < 0) dayOfWeek = 6;

var thisWeeksMonday = date.AddDays(-dayOfWeek).Date;
var lasWeeksMonday = thisWeeksMonday.AddDays(-7);

which can be reduced to a one-liner should you so desire (I do not recommend using this barely readable code...):

var mondayOfLastWeek  = date.AddDays(-(7 + ((int)date.DayOfWeek - 1 == -1 ? 6 : (int)date.DayOfWeek - 1)));
Related