UNPKG

@gidw/rfc3339-parser

Version:
77 lines (73 loc) 2.11 kB
/* global module, self */ (function (root) { var GidwRFC3339 GidwRFC3339 = {} GidwRFC3339.parseRFC3339 = parseRFC3339 if (typeof module === 'object' && module.exports) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = GidwRFC3339 /* c8 ignore next 4 */ } else { // Browser globals (root is window) root.GidwRFC3339 = GidwRFC3339 } function parseRFC3339 (input) { var inp, s, yymmdd, rest, lastIdx, idx, ms, localTime var hhmmss, zoneOffset, zoneMul, utcOffset if (typeof input !== 'string') return new Date(input) inp = input.trim().toUpperCase() s = inp.split(inp.includes('T') ? 'T' : ' ') yymmdd = s[0].split('-') rest = s[1] zoneOffset = '' zoneMul = 1 utcOffset = 0 if (rest) { lastIdx = rest.length - 1 if (rest.charAt(lastIdx) === 'Z') { hhmmss = rest.substring(0, lastIdx) } else { 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(':') s = hhmmss[2].split('.') ms = s[1] 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(s[0], 10), ms ? parseInt(ms, 10) : 0 ) if (zoneOffset) { s = zoneOffset.split(':') utcOffset = zoneMul * ( parseInt(s[0], 10) * 60 * 60 * 1000 + parseInt(s[1], 10) * 60 * 1000 ) } return new Date(localTime - utcOffset) } /* c8 ignore next */ }(typeof self !== 'undefined' ? self : this))