How about something like that?
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; }
In this case, iterator blocks , but can be easily rewritten to return a list instead.
Usage example:
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 smart enough to suggest that you should copy DateTimeKind as well. This is a really smart move if you plan to convert dates and times to local time later.
source share