How can I get the the date of
DayOfWeek last week?
I want to select Sunday June 23 as
I can only get is the
DayOfWeek of this week.
here's my code
DateTime today = DateTime.Now;
while (today.DayOfWeek != DayOfWeek.Sunday)
today = today.AddDays(-1);
DayOfWeek dayToFind = DayOfWeek.Sunday; today.AddDays(-1 * (int)today.DayOfWeek).AddDays(-7).AddDays((int)dayToFind);
The first AddDays backs up to the start of this week, then AddDays(-7) backs up to the start of last week, then the third AddDays advances to the day you are looking for.
DateTime today = DateTime.Today; int difference = today.DayOfWeek - DayOfWeek.Sunday; DateTime lastSunday = today.AddDays(-difference).AddDays(-(7 * 1)); // ^ number of weeks to remove
This basically says, "Go to the start of the week, then remove another 7 days".
You can set the DateTime object to a specific date by creating it with an initial date value. If you want it to be based from today rather than a specified date, just subtract a week.