JavaScript Answers

How to Round Time to the Nearest Quarter-Hour in JavaScript?

Spread the love

To round time to the nearest quarter-hour in JavaScript, we can use existing JavaScript date methods.

For instance, we can write:

const roundTimeQuarterHour = (time) => {
  const timeToReturn = new Date(time);
  timeToReturn.setMilliseconds(Math.round(timeToReturn.getMilliseconds() / 1000) * 1000);
  timeToReturn.setSeconds(Math.round(timeToReturn.getSeconds() / 60) * 60);
  timeToReturn.setMinutes(Math.round(timeToReturn.getMinutes() / 15) * 15);
  return timeToReturn;
const dt = new Date(2021, 1, 1, 1, 13, 1, 1)

to create the roundTimeQuarterHour function that takes the time to round.

In the function, we convert that to a date object with the Date constructor top create the timeToReturn date object.

Then we call setMilliseconds to set timeToReturn the nearest 1000 milliseconds.

Next, we call setSeconds to round timeToReturn to the nearest 60 seconds.

Then, we call setNMinutes to round timeToReturn to the nearest 15 minutes by getting the number of minutes from the time with getMinutes , dividing that by 15 and multiplying that by 15 again.

Therefore, the console log should log:

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

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 *