Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Split Times into Hour Blocks

I am in need of some assistance in getting 2 datetimes to split into the hour intervals between them.

This is working with 'pay' data, so it needs to be very accurate. I need to take clockin and clockout, and split them into hour intervals.

Example:

clockin = 5/25/2011 1:40:56PM

clockout = 5/25/2011 6:22:12PM

I need that to look like:

5/25/2011 1:40:56PM

5/25/2011 2:00:00PM

5/25/2011 3:00:00PM

5/25/2011 4:00:00PM

5/25/2011 5:00:00PM

5/25/2011 6:00:00PM

5/25/2011 6:22:12PM

I then plan to check those times against a 'differential' table to see fi they should have a new paycode. But I'll worry about the paycode later.

Any help splitting out the times? Prefer C#, but I also have access to MSSQL2000 (which is where we pull the original times)

like image 251
JClaspill Avatar asked Jun 03 '11 16:06

JClaspill


2 Answers

How about something like this?

static IEnumerable<DateTime> GetWorkingHourIntervals(DateTime clockIn, DateTime clockOut)
{
    yield return clockIn;

    DateTime d = new DateTime(clockIn.Year, clockIn.Month, clockIn.Day, clockIn.Hour, 0, 0, clockIn.Kind).AddHours(1);

    while (d < clockOut)
    {
        yield return d;
        d = d.AddHours(1);
    }

    yield return clockOut;
}

This uses iterator blocks but it could easily be rewritten to return a list instead.

Example use:

static void Main(string[] args)
{
    var clockIn = new DateTime(2011, 5, 25, 13, 40, 56);
    var clockOut = new DateTime(2011, 5, 25, 18, 22, 12);

    var hours = GetWorkingHourIntervals(clockIn, clockOut);

    foreach (var h in hours)
        Console.WriteLine(h);

    Console.ReadLine();
}

Output:

2011-05-25 13:40:56
2011-05-25 14:00:00
2011-05-25 15:00:00
2011-05-25 16:00:00
2011-05-25 17:00:00
2011-05-25 18:00:00
2011-05-25 18:22:12

Update: LukeH was clever enough to suggest that you should also copy the DateTimeKind. This is indeed a smart move if you're planning on converting the datetimes to/from local time later on.

like image 133
Markus Olsson Avatar answered Sep 24 '22 23:09

Markus Olsson


var hours = new List<DateTime>();
hours.Add(clockin);

var next = new DateTime(clockin.Year, clockin.Month, clockin.Day,
                        clockin.Hour, 0, 0, clockin.Kind);

while ((next = next.AddHours(1)) < clockout)
{
    hours.Add(next);
}
hours.Add(clockout);
like image 24
LukeH Avatar answered Sep 25 '22 23:09

LukeH