Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round time to the nearest quarter hour in JavaScript?

For example:

Given time: 08:22 => Rounded to: 08:15  Given time: 08:23 => Rounded to: 08:30 

Should be pretty simple. But all I was able to produce is lengthy, not very good code to solve the issue. My mind's just gone blank.

Regards

like image 566
devployment Avatar asked Feb 11 '11 11:02

devployment


People also ask

How do you round to the nearest 15 minutes?

Check out the instructions, rounding rules to round off time value to the nearest 15 minutes easily. Get the actual time. If the minutes times is above 7.5 minutes, then roun up to the full quater. If the minutes time is below 7.5 minutes, then round down.

How do you round to the nearest half hour?

How to round to the nearest half hour. Change times from 15 after through 16 before the hour to the half hour. Change times 15 before the hour through 14 after the hour to the full hour.


1 Answers

Given that you have hours and minutes in variables (if you don't you can get them from the Date instance anyway by using Date instance functions):

var m = (parseInt((minutes + 7.5)/15) * 15) % 60; var h = minutes > 52 ? (hours === 23 ? 0 : ++hours) : hours; 

minutes can as well be calculated by using Math.round():

var m = (Math.round(minutes/15) * 15) % 60; 

or doing it in a more javascript-sophisticated expression without any functions:

var m = (((minutes + 7.5)/15 | 0) * 15) % 60; var h = ((((minutes/105) + .5) | 0) + hours) % 24; 

You can check the jsPerf test that shows Math.round() is the slowest of the three while mainly the last one being the fastest as it's just an expression without any function calls (no function call overhead i.e. stack manipulation, although native functions may be treated differently in Javascript VM). //----

like image 109
Robert Koritnik Avatar answered Oct 13 '22 09:10

Robert Koritnik