Show hours pr day in a given interval example below

Viewed 17

I want to have a dynamic .net function which takes a parameter called duration and lists all the hours of a day with that given duration. E.g. if i have a duration of 90 minutes I want my out put to be

00:00
01:30
03:00 
....
22:30

and if the duration is 15 it should be

00:00
00:15
00:30
...
23.45

how would your take be on crafting this. Let me know if you have any further questions :)

1 Answers

A simple while loop should suffice (fiddle):

public static void Main()
{
    foreach (var t in GetTimesOfDay(new TimeSpan(0, 90, 0)))
    {
        Console.WriteLine(t.ToString(@"hh\:mm"));
    }
}

private static IEnumerable<TimeSpan> GetTimesOfDay(TimeSpan distance)
{
    var t = new TimeSpan(0, 0, 0);
    var fullDay = new TimeSpan(24, 0, 0);
    
    while (t < fullDay)
    {
        yield return t;
        t = t.Add(distance);
    }
}
Related