Round a Date to the Nearest Hour using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 16, 2022

banner

Photo from Unsplash

Round a Date to the Nearest Hour using JavaScript #

To round a date to the nearest hour:

  1. Use the setMinutes() method to set the minutes of the date to its current minutes + 30.
  2. Use the setMinutes() method to set the minutes, seconds and milliseconds to 0.
  3. If adding 30 minutes to the date rolls over to the next hour, the hour is rounded up, otherwise down.
index.js
function roundToNearestHour(date) { date.setMinutes(date.getMinutes() + 30); date.setMinutes(0, 0, 0); return date; } // 👇️ Sun Jan 16 2022 14:00:00 (minutes are 30) console.log(roundToNearestHour(new Date(2022, 0, 16, 13, 30, 00))); // 👇️ Sun Jan 16 2022 13:00:00 (minutes are 29) console.log(roundToNearestHour(new Date(2022, 0, 16, 13, 29, 00)));

We used the Date() constructor when logging the examples to the console. The parameters we passed are: year, month (January = 0, February = 1, etc), day of month, hours, minutes, seconds.

We created a reusable function that rounds a date and time to the nearest hour.

The setMinutes method sets the minutes on the date object.

The method takes the following 3 parameters:

  1. minutesValue - an integer between 0 and 59 that represents the minutes.
  2. secondsValue (optional) - an integer between 0 and 59 that represents the seconds.
  3. msValue (optional) - a number between 0 and 999 that represents the milliseconds.

In our first call to the setMinutes() method, we used the getMinutes() method to get the minutes of the date object and added 30 to the result.

If adding 30 minutes to the current time increments the hour value by 1, then we should round up to the next nearest hour.

On the other hand, if adding 30 minutes to the time does not increment the hour, then the time is at 29 minutes or less and we should round the minutes down to 0.

The Date object in JavaScript automatically handles the scenario where adding 30 minutes to a date and time rolls over to the next hour and possibly to the next day.

index.js
function roundToNearestHour(date) { date.setMinutes(date.getMinutes() + 30); date.setMinutes(0, 0, 0); return date; } // 👇️ Sun Jan 17 2022 00:00:00 (minutes are 30) console.log(roundToNearestHour(new Date(2022, 0, 16, 23, 30, 00)));
In the example above, we round the hour up, and the Date() object automatically rolls over to the next day because rounding the hour up changes the date.

In our second call to the setMinutes() method, we set the minutes, seconds and milliseconds to 0, to make sure the date and time object points to a round hour, e.g. 08:00:00, and not 08:00:30.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.