-2

So I need to perform a calculation that always takes the last week from today's date and defines the day that started that week until the day it ended, but I need that start day to be a Sunday and the end day to be a Saturday. That way I'll have the whole week and I can use it as a filter. I thought of ways to calculate it like this:

DateTime currentDate = DateTime.Today;
int daysUntilLastSunday = (currentDate.DayOfWeek - DayOfWeek.Sunday + 7) % 7;

DateTime startOfLastWeek = currentDate.AddDays(-daysUntilLastSunday - 7).Date;
DateTime endOfLastWeek = startOfLastWeek.AddDays(6).Date.AddHours(23).AddMinutes(59).AddSeconds(59);

However, it has a flaw which is that it will always calculate 7 days so if in the case DateTime.Today is a Tuesday, the startOfLastWeek will be a Monday and the endOfLastWeek will be a Saturday. I need it to be startOfLastWeek = Sunday and endOfLastWeek = Saturday How can I calculate this?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
PHP
  • 19
  • 5

0 Answers0