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.
I know it is bit late for answer but maybe it can help someone. If you take the minutes by the following
new Date().getMinutes()
you can take the last 5 minutes by
new Date().getMinutes() - (new Date().getMinutes()%5)
Use this method to get the next 5 minute cycle using pure JS
function calculateNextCycle(interval) {
const timeStampCurrentOrOldDate = Date.now();
const timeStampStartOfDay = new Date().setHours(0, 0, 0, 0);
const timeDiff = timeStampCurrentOrOldDate - timeStampStartOfDay;
const mod = Math.ceil(timeDiff / interval);
return new Date(timeStampStartOfDay + (mod * interval));
}
console.log(calculateNextCycle(5 * 60 * 1000)); // pass in milliseconds
That's pretty simple if you already have a Date
object:
var coeff = 1000 * 60 * 5;
var date = new Date(); //or use any other date
var rounded = new Date(Math.round(date.getTime() / coeff) * coeff)
With ES6 and partial functions it can be elegant:
const roundDownTo = roundTo => x => Math.floor(x / roundTo) * roundTo;
const roundUpTo = roundTo => x => Math.ceil(x / roundTo) * roundTo;
const roundDownTo5Minutes = roundDownTo(1000*60*5);
const roundUpTo5Minutes = roundUpTo(1000*60*5);
const now = new Date();
const msdown = roundDownTo5Minutes(now)
const msup = roundUpTo5Minutes(now)
console.log(now);
console.log(new Date(msdown));
console.log(new Date(msup));
Probably less efficient but here's another alternative:
debug('Current timestamp:', timestamp);
timestamp.setMilliseconds(0);
timestamp.setSeconds(0);
timestamp.setMinutes(Math.round(timestamp.getMinutes() / 5) * 5);
debug('Rounded timestamp:', timestamp);
Current timestamp: 2019-10-22T09:47:17.989Z Rounded timestamp: 2019-10-22T09:45:00.000Z
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