javascripttime

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


Solution

  • 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). //----