-3

Suppose I have two dates: for example:

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

How can I find how many hours between the two dates are in the time span 8:00-20:00, and how many are in the span 20:00-8:00?

Ivan Aramazov
  • 167
  • 1
  • 4
  • 12
  • this [link](https://stackoverflow.com/questions/4946316/showing-difference-between-two-datetime-values-in-hours) should help you – João Paulo Amorim Feb 20 '19 at 19:45
  • 1
    This is not necessarily a clear case of duplication because it sounds like it's not asking how many hours are in the range, but how many hours within the range are within another range. – BlueMonkMN Feb 20 '19 at 19:52
  • Do you consider `8:00` and `20:00` to belong to both ranges? – Rufus L Feb 20 '19 at 20:08
  • For your sample inputs, please let us know the **actual** answer (i.e. how many hours) you are looking for. – mjwills Feb 20 '19 at 20:32

2 Answers2

1

One way to do this would be to simply loop from the first date to the second date, adding an hour on each iteration, and then incrementing a variable depending on the value of the 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...");
}

Output

![enter image description here

Rufus L
  • 36,127
  • 5
  • 30
  • 43
0

(date2 - date1).TotalHours will give you a double value of the # of hours.

dvo
  • 2,113
  • 1
  • 8
  • 19