当前位置: 动力学知识库 > 问答 > 编程问答 >

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

网友答案:

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.

网友答案:

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

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: