如何获得下周日的日期
本文关键字:日期 周日 何获得 | 更新日期: 2023-09-27 18:10:12
可能重复:
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
将返回一个表示日期的枚举值(其中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天相加,得到下一个星期天的日期。:(
DateTime dt=dateTime;
do {
dt=dt.AddDays(1);
} while(dt.DayOfWeek!= DayOfWeek.Sunday);
// 'dt' is now the next Sunday
如果日期已经是星期日,您的问题不清楚是否返回相同的日期;我认为没有,但如果我错了,请将上面的内容改为while循环。
使用递归的示例
private static DateTime GetNextSunday(DateTime dt)
{
var tomorrow = dt.AddDays(1);
if (tomorrow.DayOfWeek != DayOfWeek.Sunday)
{
GetNextSunday(tomorrow);
}
return tomorrow;
}