查找两个日期之间的小时数

时间:2019-02-20 19:43:11

标签: c#

假设我有两个约会: 例如:

DateTime date1 = new DateTime(2019, 2, 20, 16, 0, 0);
DateTime date2 = new DateTime(2019, 2, 20, 23, 0, 0);

如何找到两个日期之间的时间间隔8:00-20:00中有几个小时,以及20:00-8:00范围中有几个小时?

2 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是简单地从第一个日期循环到第二个日期,在每次迭代中增加一个小时,然后根据Hour的值递增变量:

private static void Main()
{
    DateTime date1 = new DateTime(2019, 2, 20, 16, 0, 0);
    DateTime date2 = new DateTime(2019, 2, 20, 23, 0, 0);

    var hoursInFirstRange = 0;
    var hoursInSecondRange = 0;

    // If you want to include the final hour (23) change '<' to '<=' below
    for (DateTime temp = date1; temp < date2; temp = temp.AddHours(1))
    {
        if (temp.Hour >= 8 && temp.Hour <= 20) hoursInFirstRange++;
        else hoursInSecondRange++;
    }

    Console.WriteLine($"From {date1} to {date2} there are:");
    Console.WriteLine($" - {hoursInFirstRange} hours between 8:00 and 20:00");
    Console.WriteLine($" - {hoursInSecondRange} hours between 20:00 and 8:00");

    GetKeyFromUser("\nDone! Press any key to exit...");
}

输出

![enter image description here

答案 1 :(得分:0)

(date2 - date1).TotalHours将为您提供小时数的double值。