日期时间 - 获取下周二 [英] Datetime - Get next tuesday
问题描述
如何获得下周二的日期?
How can I get the date of next Tuesday?
在 PHP 中,它就像 strtotime('next tuesday');
一样简单.
In PHP, it's as simple as strtotime('next tuesday');
.
如何在 .NET 中实现类似的功能
How can I achieve something similar in .NET
推荐答案
正如我在评论中提到的,下周二"有多种含义,但这段代码给你下周二发生, 或者今天如果已经是星期二":
As I've mentioned in the comments, there are various things you could mean by "next Tuesday", but this code gives you "the next Tuesday to occur, or today if it's already Tuesday":
DateTime today = DateTime.Today;
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysUntilTuesday = ((int) DayOfWeek.Tuesday - (int) today.DayOfWeek + 7) % 7;
DateTime nextTuesday = today.AddDays(daysUntilTuesday);
如果您想在已经是星期二的情况下给出一周的时间",您可以使用:
If you want to give "a week's time" if it's already Tuesday, you can use:
// This finds the next Monday (or today if it's Monday) and then adds a day... so the
// result is in the range [1-7]
int daysUntilTuesday = (((int) DayOfWeek.Monday - (int) today.DayOfWeek + 7) % 7) + 1;
...或者你可以使用原来的公式,但从明天开始:
... or you could use the original formula, but from tomorrow:
DateTime tomorrow = DateTime.Today.AddDays(1);
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysUntilTuesday = ((int) DayOfWeek.Tuesday - (int) tomorrow.DayOfWeek + 7) % 7;
DateTime nextTuesday = tomorrow.AddDays(daysUntilTuesday);
只是为了使它美观且多功能:
Just to make this nice and versatile:
public static DateTime GetNextWeekday(DateTime start, DayOfWeek day)
{
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysToAdd = ((int) day - (int) start.DayOfWeek + 7) % 7;
return start.AddDays(daysToAdd);
}
因此要获取今天或未来 6 天"的值:
So to get the value for "today or in the next 6 days":
DateTime nextTuesday = GetNextWeekday(DateTime.Today, DayOfWeek.Tuesday);
要获取不包括今天的下周二"的值:
To get the value for "the next Tuesday excluding today":
DateTime nextTuesday = GetNextWeekday(DateTime.Today.AddDays(1), DayOfWeek.Tuesday);
这篇关于日期时间 - 获取下周二的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!