在日期,小时和分钟之间进行迭代

时间:2019-02-17 20:19:58

标签: c# datetime

我试图在输入的两个日期之间进行迭代,并每5分钟(在工作时间内)打印一次

好像我陷入了无尽的困境,可以让我的应用在endTime停止

DateTime startDate = new DateTime(2018, 1, 1);
DateTime endDate = new DateTime(2018, 3, 1);   

// day in month
for (DateTime date = startDate; date < endDate; date = date.AddDays(1))
{
    if (date.DayOfWeek == DayOfWeek.Friday || date.DayOfWeek == DayOfWeek.Saturday)
        continue;

    //iterate every hour
    for (var hour = date; hour < hour.AddDays(1); hour = hour.AddHours(1))
    {
        if (hour.Hour < 8 || hour.Hour > 17)
            continue;

        //iterate every minute
        for (var min = date; min <= min.AddDays(1); min = min.AddMinutes(5))
        {
            Console.WriteLine(min);
        }
     }
 }

1 个答案:

答案 0 :(得分:2)

也许您太复杂了;看看这个:

var startDate = new DateTime(2018, 1, 1);
var endDate = new DateTime(2018, 3, 1);
while ((startDate = startDate.AddMinutes(5)) < endDate)
{
    if (startDate.Hour < 8 || startDate.Hour > 17 ||
        startDate.DayOfWeek == DayOfWeek.Saturday || 
        startDate.DayOfWeek == DayOfWeek.Sunday)
        continue;

    Console.WriteLine("{0:ddd, MMM dd, yyyy HH:mm}", startDate);
}

您只需要一个循环,增加5分钟,直到遇到endDate为止;在循环中,跳过所有不需要的值(周末和非工作时间)。

在这段代码中,我将startDate用作工作变量,但是您肯定可以创建一个新变量并使情况更清楚。