检查工作日是否在过去的DateTime c#

时间:2017-08-18 11:28:42

标签: c# datetime

我正在研究天气应用程序,我想在用户输入"星期二"现在是星期三,它会给我下周二的天气。

请帮忙吗?

3 个答案:

答案 0 :(得分:2)

有很多方法可以获得"下周二"但确切的解决方案取决于这个问题的答案:

  

如果今天是星期二,并且用户在星期二打字,你想要今天或下周吗?

如果答案是"今天",那么以下两个解决方案将起作用:

public static DateTime NextDateByDayOfWeek1(DayOfWeek dow)
{
    var daysUntil = ((dow - DateTime.Today.DayOfWeek) + 7) % 7;
    return DateTime.Today.AddDays(daysUntil);
}

public static DateTime NextDateByDayOfWeek2(DayOfWeek dow)
{
    var date = DateTime.Today;
    while (date.DayOfWeek != dow)
        date = date.AddDays(1);
    return date;
}

如果答案是"下周",您只需将1天添加到您在方法中使用的日期:

public static DateTime NextDateByDayOfWeek1(DayOfWeek dow)
{
    var daysUntil = ((dow - DateTime.Today.AddDays(1).DayOfWeek) + 7) % 7;
    return DateTime.Today.AddDays(1 + daysUntil);
}

public static DateTime NextDateByDayOfWeek2(DayOfWeek dow)
{
    var date = DateTime.Today.AddDays(1);
    while (date.DayOfWeek != dow)
        date = date.AddDays(1);
    return date;
}

你甚至可以概括它们:

public static DateTime NextDateByDayOfWeek1(DateTime startDate, DayOfWeek dow)
{
    var daysUntil = ((dow - startDate.DayOfWeek) + 7) % 7;
    return startDate.AddDays(daysUntil);
}

public static DateTime NextDateByDayOfWeek2(DateTime startDate, DayOfWeek dow)
{
    var date = startDate;
    while (date.DayOfWeek != dow)
        date = date.AddDays(1);
    return date;
}

如果startDate已经是正确的一周,则会返回DateTime.Today.AddDays(1)。要获得"下周的日期",只需在调用时使用DateTime.Today,否则请使用data.frame

为什么有两种解决方案?

因为"最糟糕的情况"对于基于循环的解决方案是6次迭代,而使用余数运算符的解决方案可能需要阅读此代码的人员理解一些文档。优点和缺点。

答案 1 :(得分:1)

这取决于如何选择日期,但您应该能够使用DateTime.DayOfWeek

var datetimeNow = DateTime.Now; // Wednesday

var selectedDay = Datetime.Now.AddDays(-1); //Tuesday

if(datetimeNow.DayOfWeek < selectedDay.DayOfWeek)
    selectedDay = selectedDay.AddDays(7); // Will then be the coming tuesday

希望它有意义

答案 2 :(得分:0)

DayOfWeek基于int enum,(星期日= 0 - 星期六= 7),因此可用于计算您所需日期之前的天数。

var input = DayOfWeek.Monday;

DateTime today = DateTime.Today;
int days = input - today.DayOfWeek;
days = days < 0 ? days+7 : days; // fix it if we past that day already.

var newDate = today.AddDays(days);