Is there a simple method to round up DateTime to the nearest minute? i.e.. 2011-08-11 16:58:20 becomes 2011-08-11 16:59:00
I have already tried several solutions
dt.AddMinutes((60 - dt.Minute) % 10);
but that seems to add 1 whole minute.
Is there a simple method to round up DateTime to the nearest minute? i.e.. 2011-08-11 16:58:20 becomes 2011-08-11 16:59:00
I have already tried several solutions
dt.AddMinutes((60 - dt.Minute) % 10);
but that seems to add 1 whole minute.
As @ChristofWollenhaupt mentioned in comments section
Rounding should base on the Ticks property not Second. Otherwise rounded DateTime still have different values for milliseconds
If that's the case then create new DateTime
and make correction to minutes based on ticks.
TimeSpan timeSpan = new TimeSpan(0, 0, 0, dt.Second, dt.Millisecond);
DateTime roundedDateTime = new DateTime(
dt.Year,
dt.Month,
dt.Day,
dt.Hour,
dt.Minute,
0, //Second
0, //Millisecond
dt.Kind
);
roundedDateTime.AddMinutes(timeSpan.Ticks > 0 ? 1 : 0);