Convert iso timestamp to date format with Javascript?

45,222

Solution 1

Pass it to the Date constructor.

> var date = new Date('2012-04-15T18:06:08-07:00')
> date
  Mon Apr 16 2012 04:06:08 GMT+0300 (EEST)

For more information about Date, check https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date.

Solution 2

The newest version of javascript (v1.85 or higher in some of the latest browsers) can handle the ISO dates directly so you can just pass your string directly to the Date() constructor like this:

var jsDate = new Date("2012-04-15T18:06:08-07:00");

But older browsers (any version of IE before IE9, any version of Firefox before 4, etc...) do not support this. For those browsers, you can either get a library that can do this for you like datejs or parse it yourself like this:

var t = "2012-04-15T18:06:08-07:00";

function convertDate(t) {
    var dateRE = /(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+)([+\-]\d+):(\d+)/;
    var match = t.match(dateRE);
    var nums = [], item, date;
    if (match) {
        for (var i = 1; i < match.length; i++) {
            nums.push(parseInt(match[i], 10));
        }
        if (nums[7] < 0) {
            nums[8] *= -1;
        }
        return(new Date(nums[0], nums[1] - 1, nums[2], nums[3] - nums[6], nums[4] - nums[7], nums[5]));
    }
}

var jsDate = convertDate(t);

Working demo here: http://jsfiddle.net/jfriend00/QSgn6/

Share:
45,222
Ian
Author by

Ian

Updated on February 26, 2020

Comments

  • Ian
    Ian about 4 years

    This seems like a pretty simple question but I can't seem to get an answer for it. How can I convert an iso timestamp to display the date/time using JavaScript?

    Example timestamp: 2012-04-15T18:06:08-07:00

    Any help is appreciated, Google is failing me. Thank you.

  • Ian
    Ian about 12 years
    Well that was significantly easier than I thought it was... thanks
  • jfriend00
    jfriend00 about 12 years
    This does not appear to work in any version of IE before IE9 or versions of Firefox before Firefox 4.
  • eagleflo
    eagleflo about 12 years
    Indeed, parsing ISO dates is part of supporting EcmaScript 5. If you need to work with older browsers you're better off using something like the code below.