日期时间 - 获得下周二 [英] Datetime - Get next tuesday
问题描述
我怎样才能得到下周二的日期?
How can I get the date of next Tuesday?
在PHP中,它就是这么简单的strtotime(下周二);
。
In PHP, it's as simple as strtotime('next tuesday');
.
我怎样才能实现.NET类似的东西
How can I achieve something similar in .NET
推荐答案
正如我在评论中所提到的,有各种各样的东西,你可以通过下周二的意思,但这个code给你下一个周二发生的,还是今天,如果它已经星期二:
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屋!