Update
If you can't use moment.js and you can rely on the format of your input being as described, then consider parsing it yourself with something like this:
function parseDate(input) {
return new Date(Date.UTC(
parseInt(input.slice(0, 4), 10),
parseInt(input.slice(4, 6), 10) - 1,
parseInt(input.slice(6, 8), 10),
parseInt(input.slice(9, 11), 10),
parseInt(input.slice(11, 13), 10),
parseInt(input.slice(13,15), 10)
));
}
console.log(parseDate('20130208T080910Z'));
It's fairly straightforward to slice out the composite parts. The only quirks are that January is the 0-th month (hence the - 1
) and that the Date constructor assumes your parameters are for local time, so we follow the advice given in the Date
documentation:
Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date(
Date.UTC(...)
)
with the same arguments.
I left out format checking, but if you need it, you could define a regular expression to check your input (I'd recommend something no more complex than /^[0-9]{8}T[0-9]{6}Z$/
, and then just let Date.UTC(...)
do its thing).
Old answer, updated to specify format string explicitly
If you can use moment.js, it already supports parsing this format:
console.log(moment('20130208T080910Z', 'YYYYMMDDTHHmmssZ'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>