ohyeah ohyeah - 4 months ago 11
C# Question

DateTime go to first occurrence of hour/minute/second

Given this datetime of January 1 2015 at 23:00 hours:

var someDate = new DateTime(2015, 1, 1, 23, 0, 0);


And given the int
6
, which is the desired hour, how do I return the first following datetime where the hour is
6
? In this case,
someDate
and
6
would return a new DateTime of January 2 2015 at 06:00 hours.

Answer

I would simply add the hours to the original date and add another day if the result is before the original time:

var someDate = new DateTime(2015, 1, 1, 23, 0, 0);
var result = someDate.Date.AddHours(6); // note the "Date" part
if (result < someDate) result = result.AddDays(1);