如何得到下个星期天的date?

可能重复:
ASP.net得到下一个星期二

考虑到这个月的某一天,我怎么能从那一天获得下一个星期天?

所以如果我在2011年9月13日星期二通过,它将于9月18日返回。

我使用这种扩展方法:

  public static DateTime Next(this DateTime from, DayOfWeek dayOfWeek) { int start = (int)from.DayOfWeek; int target = (int)dayOfWeek; if (target <= start) target += 7; return from.AddDays(target - start); } 

date.AddDays(7 - (int)date.DayOfWeek)应该这样做,我想。

date.DayOfWeek将返回一个表示date的枚举值(其中0表示星期日)。

  var date = DateTime.Now; var nextSunday = date.AddDays(7 - (int) date.DayOfWeek); 

如果你需要最近的星期天,代码有点不同(如果你是星期天,最近的星期天是今天):

 var nearestSunday = date.AddDays(7 - date.DayOfWeek == DayOfWeek.Sunday ? 7 : date.DayOfWeek); 
 /// <summary> /// Finds the next date whose day of the week equals the specified day of the week. /// </summary> /// <param name="startDate"> /// The date to begin the search. /// </param> /// <param name="desiredDay"> /// The desired day of the week whose date will be returneed. /// </param> /// <returns> /// The returned date is on the given day of this week. /// If the given day is before given date, the date for the /// following week's desired day is returned. /// </returns> public static DateTime GetNextDateForDay( DateTime startDate, DayOfWeek desiredDay ) { // (There has to be a better way to do this, perhaps mathematically.) // Traverse this week DateTime nextDate = startDate; while( nextDate.DayOfWeek != desiredDay ) nextDate = nextDate.AddDays( 1D ); return nextDate; } 

资源:

http://angstrey.com/index.php/2009/04/25/finding-the-next-date-for-day-of-week/

代码如下:

 int dayOfWeek = (int) DateTime.Now.DayOfWeek; DateTime nextSunday = DateTime.Now.AddDays(7 - dayOfWeek).Date; 

首先获取星期几的数值,例如:星期二= 2

然后从星期天减去它,7 – 2 = 5天join到下一个星期天date。 🙂

 DateTime dt=dateTime; do { dt=dt.AddDays(1); } while(dt.DayOfWeek!= DayOfWeek.Sunday); // 'dt' is now the next Sunday 

如果date已经是星期天,你的问题还不清楚是否返回相同的date; 我假设不,但如果我错了,将上面的内容改为while循环。

使用recursion的例子

  private static DateTime GetNextSunday(DateTime dt) { var tomorrow = dt.AddDays(1); if (tomorrow.DayOfWeek != DayOfWeek.Sunday) { GetNextSunday(tomorrow); } return tomorrow; } 
 public static DateTime GetNextSunday (DateTime date) { if (date.DayOfWeek == DayOfWeek.Sunday) date = date.AddDays(1); while (date.DayOfWeek != DayOfWeek.Sunday) date = date.AddDays(1); return date; }