Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 600
Jick Lee Avatar asked May 28 '12 19:05

Jick Lee


People also ask

How do you round to the nearest 5 in JavaScript?

To round a number to the nearest 5, call the Math. round() function, passing it the number divided by 5 and multiply the result by 5 .

How do you round a date in JavaScript?

To round a date to the nearest hour: Use the setMinutes() method to set the minutes of the date to its current minutes + 30 . Use the setMinutes() method to set the minutes, seconds and milliseconds to 0 .

How do you round to the nearest minute?

You also can use this formula =MROUND(A2,15/60/24) to round time to nearest minute.


1 Answers

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) 
like image 140
Tomasz Nurkiewicz Avatar answered Sep 21 '22 10:09

Tomasz Nurkiewicz