How to round to nearest hour using JavaScript Date Object

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

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

Tags:

Javascript