Using a Date() instance, how might I round a time to the nearest five minutes?
For example: if it\'s 4:47 p.m. it\'ll set the time to 4:45 p.m.
recently found a very efficient way to round off the date to a timeframe
in short:
// minutes
var tf = 15; // 5,10,13,15, 60, - what ever you want
var dt = DateTime.UtcNow;
var minues = dt.TimeOfDay.TotalMinutes; // use TotalMinutes, TotalSecibds, TotalMillisecons and etc
var roundedMinutes = (minues - (minues%tf));
var roundedDate = dt.Date.AddMinutes(a);
I bit of my testing in LINQPad
// minutes
var tf = 15; // 5,10,13,15, 60, - what ever you want
var dt = DateTime.UtcNow;
var minues = dt.TimeOfDay.TotalMinutes;
dt.Dump();
minues.Dump();
(ms%tf).Dump();
var a = (minues - (minues%tf));
a.Dump();
dt.Date.AddMinutes(a).Dump();
output:
13.07.2018 7:43:58 - current date
463,981443103333 - total mins
13,9814431033333 - rest
450 - rounded minutes value
13.07.2018 7:30:00 - rounded date