Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate previous week's start and end date

Tags:

c#

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.

like image 362
Henryk Avatar asked Mar 18 '09 13:03

Henryk


2 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.

like image 192
bstoney Avatar answered Oct 20 '22 11:10

bstoney


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.

like image 27
mqp Avatar answered Oct 20 '22 10:10

mqp