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.
There is an NPM package @qc/date-round
that can be used. Given that you have a Date
instance to be rounded
import { round } from '@qc/date-round'
const dateIn = ...; // The date to be rounded
const interval = 5 * 60 * 1000; // 5 minutes
const dateOut = round(dateIn, interval)
Then you can use date-fns to format the date
import format from 'date-fns/format';
console.log(format(dateOut, 'HH:mm')) // 24-hr
console.log(format(dateOut, 'hh:mm a')) // 12-hr
Here is a method that will round a date object to the nearest x minutes, or if you don't give it any date it will round the current time.
let getRoundedDate = (minutes, d=new Date()) => {
let ms = 1000 * 60 * minutes; // convert minutes to ms
let roundedDate = new Date(Math.round(d.getTime() / ms) * ms);
return roundedDate
}
// USAGE //
// Round existing date to 5 minutes
getRoundedDate(5, new Date()); // 2018-01-26T00:45:00.000Z
// Get current time rounded to 30 minutes
getRoundedDate(30); // 2018-01-26T00:30:00.000Z