Question

I have two times like

Time A:09:00 AM

and Time B:06:00 PM I want to get the total hours between Time A and Time B and show it with the time span of 1 hour e.g:

09:00 AM

10:00 AM

11:00 AM

12:00 PM

upto

06:00 PM
Was it helpful?

Solution

I think you need something like;

DateTime dt1 = DateTime.Parse("09:00 AM");
DateTime dt2 = DateTime.Parse("06:00 PM");
while (dt1 <= dt2)
{
     Console.WriteLine(dt1.ToString("hh:mm tt"));
     dt1 = dt1.AddHours(1);
}

Output will be;

09:00 AM
10:00 AM
11:00 AM
12:00 PM
01:00 PM
02:00 PM
03:00 PM
04:00 PM
05:00 PM
06:00 PM

Here's a demonstration.

I'm sorry but I don't understand why you interested in TimeSpan on this case. It is a duration in time. You need to get every hour times with DateTime.

OTHER TIPS

Use this function:

public static IEnumerable<DateTime> GetHours(DateTime startTime, DateTime endTime)
{
    var currentTime = startTime;

    while (currentTime <= endTime)
    {
        yield return currentTime;
        currentTime = currentTime.AddHours(1);
    }
}

If you just need the number of hours between two events, you can use a variation of

(endTime - startTime).TotalHours

This will return a double. To calculate the number of items returned from the iterator, use

(int)(endTime - startTime).TotalHours + 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top