Carlo Adap
Carlo Adap

Reputation: 69

Select DayOfWeek Last Week

How can I get the the date of DayOfWeek last week?

for example

I want to select Sunday June 23 as DayOfWeek?

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

Upvotes: 2

Views: 194

Answers (3)

bitfiddler
bitfiddler

Reputation: 2115

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.

Upvotes: 0

Simon Whitehead
Simon Whitehead

Reputation: 65049

Perhaps this:

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

Upvotes: 2

Michael Bray
Michael Bray

Reputation: 15265

How about:

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.

Upvotes: 2

Related Questions