如何获取每个月和每年特定日期的日期?

时间:2014-06-03 05:26:19

标签: c# .net asp.net-mvc

想要了解这些年中每个月的周一,周三和周六的日期。 我试图以这种方式管理它;

DateTime today = DateTime.UtcNow;
int deltaMonday = DayOfWeek.Monday - today.DayOfWeek;
var monday = today.AddDays(deltaMonday);


int deltaWednesday = DayOfWeek.Wednesday - today.DayOfWeek;
var wednesday = today.AddDays(deltaWednesday);

int deltaSaturday = DayOfWeek.Saturday - today.DayOfWeek;
var saturday = today.AddDays(deltaSaturday);

但我希望显示下一个(例如)星期一的日期,如果这个(星期)的星期一去世,同样的星期三和星期六也是如此。如果(当前)月份过去,则应显示下个月的日期。有没有更短的方法来获取或更改我的代码?

3 个答案:

答案 0 :(得分:2)

试试这个 -

 DateTime today = DateTime.UtcNow;
 int deltaMonday = DayOfWeek.Monday - today.DayOfWeek;
 var monday = today.AddDays(deltaMonday += deltaMonday < 0 ? 7 : 0);

 int deltaWednesday = DayOfWeek.Wednesday - today.DayOfWeek;
 var wednesday = today.AddDays(deltaWednesday += deltaWednesday < 0 ? 7 : 0);

 int deltaSaturday = DayOfWeek.Saturday - today.DayOfWeek;
 var saturday = today.AddDays(deltaSaturday += deltaSaturday < 0 ? 7 : 0);

简而言之,如果这一天过去了,那就是差异是负面的,那么只需要加7天。

如果需要检查几个月,请做类似的事情。

答案 1 :(得分:1)

试试这个 -

 Public DateTime GetNextWeekday(DayOfWeek day)
 {
     DateTime result = DateTime.Now.AddDays(1);
     while( result.DayOfWeek != day )
          result = result.AddDays(1);
     return result;
 }

 DateTime deltaMonday=GetNextWeekday(1)
 DateTime deltaWednesday=GetNextWeekday(3)
 DateTime deltaSaturday=GetNextWeekday(6)

答案 2 :(得分:0)

如果你知道需要多少天才能看,你可以使用linq。下面的代码在接下来的100天内查找所有星期一,星期三和星期六:

var daysAhead = Enumerable.Range(0, 100);
var dates = daysAhead.Select (a => DateTime.Today.AddDays(a))
                         .Where (a => a.DayOfWeek == DayOfWeek.Monday ||
                                      a.DayOfWeek == DayOfWeek.Wednesday ||
                                      a.DayOfWeek == DayOfWeek.Saturday ).ToList();