答案 0 :(得分:87)
我使用这种扩展方法:
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);
}
答案 1 :(得分:24)
date.AddDays(7 - (int)date.DayOfWeek)
应该这样做。
date.DayOfWeek
将返回表示日期的枚举值(其中0表示星期日)。
答案 2 :(得分:6)
var date = DateTime.Now;
var nextSunday = date.AddDays(7 - (int) date.DayOfWeek);
如果你需要最近的星期日,代码有点不同(好像你星期天,最近的星期日是今天):
var nearestSunday = date.AddDays(7 - date.DayOfWeek == DayOfWeek.Sunday ? 7 : date.DayOfWeek);
答案 3 :(得分:3)
/// <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/
答案 4 :(得分:2)
以下是代码:
int dayOfWeek = (int) DateTime.Now.DayOfWeek;
DateTime nextSunday = DateTime.Now.AddDays(7 - dayOfWeek).Date;
首先获取星期几的数值,例如:星期二= 2
然后从星期日减去它,7-2 = 5天加入以获得下一个星期日。 :)
答案 5 :(得分:0)
DateTime dt=dateTime;
do {
dt=dt.AddDays(1);
} while(dt.DayOfWeek!= DayOfWeek.Sunday);
// 'dt' is now the next Sunday
如果日期已经是星期日,您的问题不清楚是否返回相同的日期;我假设没有,但如果我错了,请将上述内容更改为while循环。
答案 6 :(得分:0)
使用递归的示例
private static DateTime GetNextSunday(DateTime dt)
{
var tomorrow = dt.AddDays(1);
if (tomorrow.DayOfWeek != DayOfWeek.Sunday)
{
GetNextSunday(tomorrow);
}
return tomorrow;
}
答案 7 :(得分:0)
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;
}