@gidw/rfc3339-parser
Version:
RFC3339 parser
59 lines (57 loc) • 1.52 kB
JavaScript
/* eslint-env es6 */
export function parseRFC3339 (input) {
let hhmmss, zoneOffset, zoneMul, utcOffset
if (typeof input !== 'string') return new Date(input)
const inp = input.trim().toUpperCase()
const s1 = inp.split(inp.includes('T') ? 'T' : ' ')
const yymmdd = s1[0].split('-')
const rest = s1[1]
zoneOffset = ''
zoneMul = 1
utcOffset = 0
if (rest) {
const length = rest.length
if (rest.charAt(length - 1) === 'Z') {
hhmmss = rest.substring(0, length - 1)
} else {
let idx = rest.indexOf('+')
if (idx > -1) {
hhmmss = rest.substring(0, idx)
zoneOffset = rest.substring(idx + 1)
zoneMul = 1
} else {
idx = rest.indexOf('-')
if (idx > -1) {
hhmmss = rest.substring(0, idx)
zoneOffset = rest.substring(idx + 1)
zoneMul = -1
} else {
hhmmss = rest
}
}
}
}
if (!hhmmss) return new Date(input)
hhmmss = hhmmss.split(':')
const s2 = hhmmss[2].split('.')
const ss = s2[0]
const ms = s2[1]
const localTime = Date.UTC(
parseInt(yymmdd[0], 10),
parseInt(yymmdd[1], 10) - 1,
parseInt(yymmdd[2], 10),
parseInt(hhmmss[0], 10),
parseInt(hhmmss[1], 10),
parseInt(ss, 10),
ms ? parseInt(ms, 10) : 0
)
if (zoneOffset) {
const s3 = zoneOffset.split(':')
utcOffset = zoneMul *
(
parseInt(s3[0], 10) * 60 * 60 * 1000 +
parseInt(s3[1], 10) * 60 * 1000
)
}
return new Date(localTime - utcOffset)
}