如何获取下周二的日期?
在 PHP 中,它就像 strtotime('next tuesday');
一样简单。
我怎样才能在 .NET 中实现类似的东西
最佳答案
正如我在评论中提到的,“下周二”可能有多种含义,但此代码为您提供了“下周二发生,如果已经是周二,则为今天”:
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);
如果你想在已经是星期二的情况下给出“一周的时间”,你可以使用:
// 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;
...或者您可以使用原始公式,但从明天开始:
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);
编辑:只是为了使它美观且用途广泛:
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 天”的值:
DateTime nextTuesday = GetNextWeekday(DateTime.Today, DayOfWeek.Tuesday);
获取“下周二不包括今天”的值:
DateTime nextTuesday = GetNextWeekday(DateTime.Today.AddDays(1), DayOfWeek.Tuesday);
关于c# - 计算即将到来的工作日的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6346119/