小编典典

计算即将到来的工作日的 DateTime

all

我怎样才能得到下周二的日期?

在 PHP 中,它就像strtotime('next tuesday');.

如何在 .NET 中实现类似的功能


阅读 58

收藏
2022-07-28

共1个答案

小编典典

正如我在评论中提到的那样,“下周二”可能意味着各种不同的事情,但这段代码为您提供“下周二发生,或者今天如果已经是周二”:

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);
2022-07-28