Jick Lee
Jick Lee

Reputation: 1049

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

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.

Upvotes: 99

Views: 58851

Answers (10)

phhu
phhu

Reputation: 1982

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')
// OR: import roundToNearestMinutes from 'date-fns/roundToNearestMinutes'
console.log(roundToNearestMinutes(new Date(), {nearestTo: 5}));
// e.g. 2021-05-19T22:45:00.000Z

Upvotes: 5

joshuakcockrell
joshuakcockrell

Reputation: 6143

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.

function 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

Upvotes: 23

peter.bartos
peter.bartos

Reputation: 12045

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));

Upvotes: 20

I.G. Pascual
I.G. Pascual

Reputation: 6005

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

Upvotes: 0

Shubham Rai
Shubham Rai

Reputation: 39

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

Upvotes: 1

Malvineous
Malvineous

Reputation: 27340

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

Upvotes: 3

Danny Hurlburt
Danny Hurlburt

Reputation: 742

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

Upvotes: 0

Vladimir Semashkin
Vladimir Semashkin

Reputation: 1280

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

Upvotes: 0

user3767296
user3767296

Reputation: 239

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)

Upvotes: 6

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340933

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)

Upvotes: 269

Related Questions