-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
58 lines (44 loc) · 1.17 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
var periods = [
'Milliseconds',
'Seconds',
'Minutes',
'Hours',
'Date',
'Month',
'FullYear'
]
var dateIndex = periods.indexOf('Date')
var getters = periods.map(function (name) {
return Date.prototype['getUTC'+name]
})
var setters = periods.map(function (name) {
return Date.prototype['setUTC'+name]
})
function index (period) {
var j = periods.indexOf(period)
if(!~j) throw new Error('period must be one of:' + periods)
return j
}
exports.floor = function (time, period) {
var d = new Date(time)
var j = index(period)
for(var i = 0; i < j; i++)
setters[i].call(d, i == dateIndex ? 1 : 0)
return 'number' === typeof time ? +d : d
}
exports.ceil = function (time, period) {
var d = new Date(time)
var j = index(period)
for(var i = 0; i < j; i++)
setters[i].call(d, i == dateIndex ? 1 : 0)
do {
var v = getters[j].call(d)
setters[j].call(d, v + 1)
} while(v == getters[j++].call(d))
return 'number' === typeof time ? +d : d
}
exports.periods = periods
periods.forEach(function (k) {
exports.floor[k] = function (time) { return exports.floor(time, k) }
exports.ceil[k] = function (time) { return exports.ceil(time, k) }
})