Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round to nearest hour using JavaScript Date Object

Tags:

javascript

I am working on a project that requires a time in the future to be set using the Date object.

For example:

futureTime = new Date();
futureTime.setHours(futureTime.getHours()+2);

My questions is; once the future date is set, how can I round to the closest full hour and then set the futureTime var with it?

For example:

Given 8:55 => var futureTime = 9:00
Given 16:23 => var futureTime = 16:00

Any help would be appreciated!

like image 585
dSquared Avatar asked Sep 03 '11 13:09

dSquared


People also ask

How do you round date and time?

Rounding Up Date Objects Round up to the next closest rounding unit boundary. For example, if the rounding unit is month then next closest boundary of 2000-01-01 is 2000-02-01 00:00:00 .

What is date now () in JavaScript?

now() The static Date. now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.


5 Answers

Round the minutes and then clear the minutes:

var date = new Date(2011,1,1,4,55); // 4:55
roundMinutes(date); // 5:00

function roundMinutes(date) {

    date.setHours(date.getHours() + Math.round(date.getMinutes()/60));
    date.setMinutes(0, 0, 0); // Resets also seconds and milliseconds

    return date;
}
like image 136
Joe Avatar answered Oct 05 '22 21:10

Joe


The other answers ignore seconds and milliseconds components of the date.

The accepted answer has been updated to handle milliseconds, but it still does not handle daylight savings time properly.

I would do something like this:

function roundToHour(date) {
  p = 60 * 60 * 1000; // milliseconds in an hour
  return new Date(Math.round(date.getTime() / p ) * p);
}

var date = new Date(2011,1,1,4,55); // 4:55
roundToHour(date); // 5:00

date = new Date(2011,1,1,4,25); // 4:25
roundToHour(date); // 4:00
like image 26
Felix Livni Avatar answered Oct 05 '22 22:10

Felix Livni


A slightly simpler way :

var d = new Date();
d.setMinutes (d.getMinutes() + 30);
d.setMinutes (0);
like image 32
HBP Avatar answered Oct 05 '22 22:10

HBP


Another solution, which is no where near as graceful as IAbstractDownvoteFactory's

var d = new Date();
if(d.getMinutes() >= 30) {
   d.setHours(d.getHours() + 1);
}
d.setMinutes(0);
like image 35
JamesHalsall Avatar answered Oct 05 '22 21:10

JamesHalsall


Or you could mix the two for optimal size. http://jsfiddle.net/HkEZ7/

function roundMinutes(date) {
    return date.getMinutes() >= 30 ? date.getHours() + 1 : date.getHours();
}
like image 21
rlemon Avatar answered Oct 05 '22 22:10

rlemon