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 we
You could create a DateTime Extension method, that can be used with a DayOfWeek parameter:
public static class DateTimeExtension
{
public static DateTime GetPreviousWeekDay(this DateTime currentDate, DayOfWeek dow)
{
int currentDay = (int)currentDate.DayOfWeek, gotoDay = (int)dow;
return currentDate.AddDays(-7).AddDays(gotoDay-currentDay);
}
}
Then use it as follows:
DateTime testDate = new DateTime(2017, 01, 21);
Console.WriteLine(testDate.GetPreviousWeekDay(DayOfWeek.Sunday));
Console.WriteLine(testDate.GetPreviousWeekDay(DayOfWeek.Saturday));
To use it to get the previous week from the current date (as asked in the question):
var prevWkStartDate = DateTime.Now.GetPreviousWeekDay(DayOfWeek.Monday);
var prevWkEndDate = DateTime.Now.GetPreviousWeekDay(DayOfWeek.Sunday);
Console.Write($"Previous week starts at {prevWkStartDate.ToShortDateString()}");
Console.WriteLine($" and ends at {prevWkEndDate.ToShortDateString()}");
Update: Seems that this requires a fix (example date: 10th December 2020):
public static DateTime GetPreviousWeekDay(this DateTime currentDate, DayOfWeek dow)
{
int d = 0; if (dow == DayOfWeek.Sunday) { dow = DayOfWeek.Saturday; d = 1; }
int currentDay = (int)currentDate.DayOfWeek, gotoDay = (int)dow;
return currentDate.AddDays(-7).AddDays(gotoDay - currentDay + d);
}