Round a Date() to the nearest 5 minutes in javascript

Javascript

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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)

Solution 2 - Javascript

Round to nearest x minutes

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

Solution 3 - Javascript

With ES6 and partial functions it can be elegant. Choose if need to round to closest or always down/up:

const roundTo = roundTo => x => Math.round(x / roundTo) * roundTo;    
const roundDownTo = roundTo => x => Math.floor(x / roundTo) * roundTo;
const roundUpTo = roundTo => x => Math.ceil(x / roundTo) * roundTo;

const roundTo5Minutes = roundTo(1000 * 60 * 5);
const roundDownTo5Minutes = roundDownTo(1000 * 60 * 5);
const roundUpTo5Minutes = roundUpTo(1000 * 60 * 5);

const now = new Date();
const msRound = roundTo5Minutes(now)
const msDown = roundDownTo5Minutes(now)
const msUp = roundUpTo5Minutes(now)

console.log(now);
console.log(new Date(msRound));
console.log(new Date(msDown));
console.log(new Date(msUp));

Solution 4 - Javascript

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)

Solution 5 - Javascript

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

Solution 6 - Javascript

Date-fns now has a function which will round minutes on dates. See https://date-fns.org/v2.21.3/docs/roundToNearestMinutes

const roundToNearestMinutes = require('date-fns/roundToNearestMinutes')
console.log(roundToNearestMinutes(new Date(), {nearestTo: 5}));
// e.g. 2021-05-19T22:45:00.000Z

Solution 7 - Javascript

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

Solution 8 - Javascript

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

Solution 9 - Javascript

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

Solution 10 - Javascript

One line solution (round up or down):

const fixedTime = (isRoundUp ? Math.ceil : Math.floor)(time / 60_000 / minutesRange)) * 60_000 * minutesRange;

// minutesRange: number -> 1, 5, 15, 30, etc // minutes
// isRoundUp: boolean
// time: number // millis

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJick LeeView Question on Stackoverflow
Solution 1 - JavascriptTomasz NurkiewiczView Answer on Stackoverflow
Solution 2 - JavascriptjoshuakcockrellView Answer on Stackoverflow
Solution 3 - Javascriptpeter.bartosView Answer on Stackoverflow
Solution 4 - Javascriptuser3767296View Answer on Stackoverflow
Solution 5 - JavascriptMalvineousView Answer on Stackoverflow
Solution 6 - JavascriptphhuView Answer on Stackoverflow
Solution 7 - JavascriptShubham RaiView Answer on Stackoverflow
Solution 8 - JavascriptVladimir SemashkinView Answer on Stackoverflow
Solution 9 - JavascriptDanny HurlburtView Answer on Stackoverflow
Solution 10 - JavascriptI.G. PascualView Answer on Stackoverflow