JavaScript Answers

How to Round to Nearest Hour Using JavaScript Date Object?

Spread the love

To round to nearest hour using JavaScript Date Object, we can call setHours to round the hour of the date to the nearest hour.

And we call setMinutes to set the minutes, seconds, and milliseconds of a date all to 0.

For instance, we can write:

const roundMinutes = (date) => {
  date.setHours(date.getHours() + Math.round(date.getMinutes() / 60));
  date.setMinutes(0, 0, 0);
  return date;

const date = new Date(2021, 1, 1, 4, 55);
const newDate = roundMinutes(date);

We create the roundMinutes which takes a date object.

In the function, we call date.setHours with date.getHours() + Math.round(date.getMinutes() / 60).

We get the hour of the date with getHours. Then we add Math.round(date.getMinutes() / 60) to add one hour if date.getMinutes() / 60 is 0.5 or bigger.

Then we call setMinutes with 3 zeroes to set the minutes, seconds, and milliseconds all to 0 respectively.

Therefore, when we call roundMinutes with date, we get:

Mon Feb 01 2021 05:00:00 GMT-0800 (Pacific Standard Time)

from the console log.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *