-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathindex.js
82 lines (69 loc) · 1.98 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
'use strict'
var DATE_TIME = /(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?/
var DATE = /^(\d{1,})-(\d{2})-(\d{2})$/
var TIME_ZONE = /([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/
var BC = /BC$/
var INFINITY = /^-?infinity$/
module.exports = function parseDate (isoDate) {
if (INFINITY.test(isoDate)) {
// Capitalize to Infinity before passing to Number
return Number(isoDate.replace('i', 'I'))
}
var matches = DATE_TIME.exec(isoDate)
if (!matches) {
// Force YYYY-MM-DD dates to be parsed as local time
return DATE.test(isoDate) ?
getDate(isoDate) :
null
}
var isBC = BC.test(isoDate)
var year = parseInt(matches[1], 10)
var isFirstCentury = year > 0 && year < 100
year = (isBC ? '-' : '') + year
var month = parseInt(matches[2], 10) - 1
var day = matches[3]
var hour = parseInt(matches[4], 10)
var minute = parseInt(matches[5], 10)
var second = parseInt(matches[6], 10)
var ms = matches[7]
ms = ms ? 1000 * parseFloat(ms) : 0
var date
var offset = timeZoneOffset(isoDate)
if (offset != null) {
var utc = Date.UTC(year, month, day, hour, minute, second, ms)
date = new Date(utc - offset)
} else {
date = new Date(year, month, day, hour, minute, second, ms)
}
if (isFirstCentury) {
date.setUTCFullYear(year)
}
return date
}
function getDate (isoDate) {
var matches = DATE.exec(isoDate)
var year = parseInt(matches[1], 10)
var month = parseInt(matches[2], 10) - 1
var day = matches[3]
// YYYY-MM-DD will be parsed as local time
var date = new Date(year, month, day)
date.setFullYear(year)
return date
}
// match timezones:
// Z (UTC)
// -05
// +06:30
function timeZoneOffset (isoDate) {
var zone = TIME_ZONE.exec(isoDate.split(' ')[1])
if (!zone) return
var type = zone[1]
if (type === 'Z') {
return 0
}
var sign = type === '-' ? -1 : 1
var offset = parseInt(zone[2], 10) * 3600 +
parseInt(zone[3] || 0, 10) * 60 +
parseInt(zone[4] || 0, 10)
return offset * sign * 1000
}