[jQuery] jQuery 에서 시간값 반올림

Posted by RAY.D
2015. 4. 27. 10:25 Web/javascript / jQuery
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.




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


Given that you have hours and minutes in variables (if you don't you can get them from the Dateinstance 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).




방법은 여러가지 있고, 계산만 잘하면 된다.


내 경우엔 round(반올림)이 아니라 ceil(올림) 으로 했고 10분단위로 끊도록 변형해서 사용했다.