c# - 计算即将到来的工作日的日期时间

标签 c# .net date

如何获取下周二的日期?

在 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/

相关文章:

C#:将 COMP-3 压缩十进制转换为人类可读的值

.net - 如何更改 Orchard 记录库

c# - 使用 .NET/WMI 获取 PC 的显示器信息

c# - GeolocationAccessStatus 更改事件不会引发

c# - 请解释定时器事件异步/等待语法

c# - EF 4.0 实体属性 setter 抛出 ArgumentOutRangeException

java - 预订逻辑不起作用

c# - 如何在 C# 中将流保存到文件?

python - 如何匹配字符串中的日期模式

CakePHP 月份名称翻译