Open In App

How to Round Time to the Nearest Quarter Hour using JavaScript ?

We have given a time and the task is to round the time to the nearest quarter-hour with the help of JavaScript. There are two approaches that are discussed below:

Approach 1: Use getMinutes() and getHours() methods to get the minutes and hours in a variable (Ex. mins, hrs) add the 7.5 to mins, divide it by 15, take the integer value and multiply it by 15, which will give the nearest quarter of minutes. If this value goes beyond 60, then take the mod with 60. For hrs, if mins 52 and if the hrs == 23, set hrs to 0 else increment its value by 1.

Approach 2: Use getMinutes() and getHours() methods to get the minutes and hours in a variable (Ex. mins, hrs). Divide mins by 15, take the round value by Math.round() and multiply it by 15, which will give the nearest quarter of minutes. If this value goes beyond 60, then take the mod with 60. For hrs, if mins 52 and if the hrs == 23, set hrs to 0 else increment its value by 1.


Article Tags :