[jQuery] jQuery 에서 시간값 반올림
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 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).
방법은 여러가지 있고, 계산만 잘하면 된다.
내 경우엔 round(반올림)이 아니라 ceil(올림) 으로 했고 10분단위로 끊도록 변형해서 사용했다.
'Web > javascript / jQuery' 카테고리의 다른 글
[jQuery] 셀렉트박스안의 모든 옵션의 value 를 가져오는 방법 (2) | 2015.04.27 |
---|---|
[jQuery] 여러 버튼의 클릭에 이벤트 바인딩 하는 방법 (2) | 2015.04.27 |
[jquery] JavaScript Array splice() Method (2) | 2015.04.16 |
[jquery] 이전 페이지, 앞 페이지로 이동 및 새로고침 (2) | 2015.04.16 |
[Troble shooting] Uncaught ReferenceError (2) | 2015.04.16 |