Search code examples
javascriptiso8601gnome-shell-extensions

Parse ISO 8601 basic datetime format in javascript


I have a date, as returned from a JSON, in the following format:

YYYYMMDDThhmmssZ

and I want to parse it in Javascript. I found some resources that cataloge this format as ISO-8601 basic format, which is slightly different from the extended format which looks like this:

YYYY-MM-DDThh:mm:ssZ

I have found some resources for how to parse the extended format, but so far I haven't found anything for parsing the basic format. Does such functionality exist in the Date module of Javascript, or so I have to use other modules (e.g. Moment)? I am asking because this is not really an option for me, as the application I am developing is a gnome-shell extension and I don't want to have any extra dependencies.


Solution

  • 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>