How to round-off hours based on Minutes(hours+0 if min<30, hours+1 otherwise)?
Just as an alternative:
public static DateTime Round( DateTime dateTime )
{
var updated = dateTime.AddMinutes( 30 );
return new DateTime( updated.Year, updated.Month, updated.Day,
updated.Hour, 0, 0, dateTime.Kind );
}
If speed is an issue, the following should be the fastest way:
static DateTime RoundToHour(DateTime dt){
long ticks = dt.Ticks + 18000000000;
return new DateTime(ticks - ticks % 36000000000, dt.Kind);
}
It's also a pretty straight-forward and simple way to do it.
To explain, a DateTime structure doesn't actually have fields that store the year, month, day, hour, minute, etc. It stores one single long
value, the number of "ticks" since a certain epoch (Jan 1, 1 AD). A tick is 100 nanoseconds, or one 10,000,000th of a second.
Any time you use any of the date/time properties, it divides by the proper constant.
So here, we add a constant equal to 30 minutes (30 * 60 * 1e7 = 18000000000 ticks), then subtract the remainder after dividing by a constant equal to one hour (60 * 60 * 1e7 = 36000000000 ticks).
What about:
public static DateTime RoundToHours(DateTime input)
{
DateTime dt = new DateTime(input.Year, input.Month, input.Day, input.Hour, 0, 0);
if (input.Minute > 29)
return dt.AddHours(1);
else
return dt;
}
No need to convert to string and back again!
EDIT:
Using a input.Hour+1
in the constructor will fail if the Hour is 23. The .AddHours(1)
will correctly result in '0:00' the next day.