pitersmx pitersmx - 1 year ago 267
C# Question

Split DateTime range into hour periods

I have a class that presents some time range (period) that starts at

Begin
and ends at
End
:

public class Period
{
public DateTime Begin { get; set; }
public DateTime End { get; set; }
}


Let's say that
Begin
=
01/07/2017 7:50:00
and
End
=
01/07/2017 12:30:00
.

What I need to get is a collection of more detailed
Period
objects from the base one that will consist of hourly-splitted periods - output for the example should be like this (Date part is omitted):

[0]
Begin = 7:50:00, End = 7:59:59


[1]
Begin = 8:00:00, End = 8:59:59


[2]
Begin = 9:00:00, End = 9:59:59


[3]
Begin = 10:00:00, End = 10:59:59


[4]
Begin = 11:00:00, End = 11:59:59


[5]
Begin = 12:00:00, End = 12:29:59


What would be the best way to do the split?

Answer Source
Period period = new Period();
period.Begin = new DateTime(2017, 7,1, 7,50,0);
period.End = new DateTime(2017, 7, 1, 12, 30, 0);

DateTime start = period.Begin;

List<Period> periods = new List<Period>();
while(start < period.End)
{
   DateTime end = start;
   end = end.AddMinutes(-end.Minute);
   end = end.AddSeconds(-1);
   end = end.AddHours(1);
   if(end > period.End)
      end = period.End;

   periods.Add(new Period{Begin = start, End = end});
   start = end.AddSeconds(1);
}

foreach(var p in periods)
{
   Console.WriteLine($"Start: {p.Begin.ToLongTimeString()} End: 
   {p.End.ToLongTimeString()}");
}

This results in

Start: 07:50:00 End: 07:59:59
Start: 08:00:00 End: 08:59:59
Start: 09:00:00 End: 09:59:59
Start: 10:00:00 End: 10:59:59
Start: 11:00:00 End: 11:59:59
Start: 12:00:00 End: 12:30:00
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download