15

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
  • 1,850
  • 6
  • 23
  • 38
  • Possible dup http://stackoverflow.com/questions/847185/convert-a-unix-timestamp-to-time-in-javascript – elclanrs Apr 16 '12 at 21:04
  • 5
    A unix timestamp and iso timestamp are not the same, so no, it's not a duplicate. – Ian Apr 16 '12 at 21:06
  • Is your ISO timestamp you have a string? and you want to parse it into a javascript `Date()` class? – jfriend00 Apr 16 '12 at 21:06
  • jfriend00, I put an example timestamp up there 2012-04-15T18:06:08-07:00. That's exactly what I what I want to do, I just want to take that timestamp, run it through javascript and have it return in date format Something like "Jan 1, 2010 12:00:21" (that timestamp wouldn't actually convert to that). However I have been unable to figure out how to do this with an iso timestamp. I know how to do this in PHP but I want to do it in JavaScript so it will be relative to the user's timezone. – Ian Apr 16 '12 at 21:11

4 Answers4

29

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.

eagleflo
  • 1,184
  • 9
  • 14
  • 1
    Well that was significantly easier than I thought it was... thanks – Ian Apr 16 '12 at 21:16
  • 6
    This does not appear to work in any version of IE before IE9 or versions of Firefox before Firefox 4. – jfriend00 Apr 16 '12 at 21:27
  • 1
    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. – eagleflo Apr 16 '12 at 21:50
4

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/

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

This is the best I've seen so far that is able to use the client's desktop timezone and changes real-time with the timezone setting:

<script type="text/javascript">
    //Use: timeZoneConvert("2015-11-03T17:36:20.970");
    //Mon Nov 02 2015 17:36:20 GMT-0600 (Central Standard Time)  [Date object]

    //To format string use: timeZoneConvertFormatted("2015-11-03T17:36:20.970")
    //November 2, 2015 5:36 PM

    //Works even when I change client timezone to Pacific Standard
    //Mon Nov 02 2015 15:36:20 GMT-0800 (Pacific Standard Time)



var months = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
function timeZoneConvert(dateStr) {
    var d = parse_iso8601(dateStr);
    //Change (- 360) constant for your server, mine is Central Standard
    var dTimezoneOffset = new Date(d.getTime() - ((new Date()).getTimezoneOffset() - 360)*60000);
    return dTimezoneOffset;
}   

function timeZoneConvertFormatted(dateStr) {
    return fDateTime(timeZoneConvert(dateStr));
}   


function fDateTime(date1) {
    var date = date1.getDate();
    var year = date1.getFullYear();
    var month = months[date1.getMonth() + 1];
    var h = date1.getHours();
    var m = date1.getMinutes();
    var ampm = "AM";
    if(m < 10) {
        m = "0" + m;
    }
    if(h > 12) {
        h = h - 12;
        var ampm = "PM";
    }
    return month + " " + date + ", " + year + " " + h + ":" + m + " " + ampm;
}



    var iso8601extended = /^\d{4}(-\d{2}(-\d{2}([T ]\d{2}(:\d{2}(:\d{2})?)?([,.]\d+)?(Z|[+-]\d{2}(:\d{2})?)?)?)?)?$/;
    var iso8601basic = new RegExp(iso8601extended.source.replace(/[:-]\\d/g, '\\d'));
    var firstNumber = /[^\d]*(\d+)/g;
    function parse_iso8601(s) {
        s = s.replace(/,/g, '.');
        var matches = iso8601extended.exec(s);
        if (matches) {
            s = s.substr(0, 10).replace(/-/g, '') + s.substr(10).replace(/:/g, '');
        }
        matches = iso8601basic.exec(s);
        if (!matches) {
            return null;
        }
        var d = new Date();
        d.setUTCFullYear(toNumber(matches[0].substring(0, 4)));
        d.setUTCMonth(matches[1] ? toNumber(matches[1].substr(0, 2)) - 1 : 0);
        d.setUTCDate(matches[2] ? toNumber(matches[2].substr(0, 2)) : 1);
        var hours = 0, minutes = 0, seconds = 0, milliseconds = 0;
        var fraction = matches[6] ? parseFloat(matches[6]) : 0;
        if (matches[3]) {
            hours = toNumber(matches[3].substr(1, 2));
            if (matches[4]) {
                minutes = toNumber(matches[4].substr(0, 2));
                if (matches[5]) {
                    seconds = toNumber(matches[5].substr(0, 2));
                    milliseconds = 1000 * fraction;
                } else {
                    seconds = 60 * fraction;
                }
            } else {
                minutes = 60 * fraction;
            }
        }
        if (!matches[7]) {
            d.setHours(hours);
            d.setMinutes(minutes);
        } else {
            d.setUTCHours(hours);
            d.setUTCMinutes(minutes);
        }
        d.setUTCSeconds(seconds);
        d.setUTCMilliseconds(milliseconds);
        if (matches[7] && matches[7] != 'Z') {
            offset = toNumber(matches[7].substr(1, 2)) * 60;
            if (matches[8]) {
                 offset += toNumber(matches[8].substr(0, 2));
            }
            d.setTime(d.getTime() + 60000 * offset * (matches[7].substr(0, 1) == '-' ? 1 : -1));
        }
        return d;
    }
    function toNumber(s) {
        return parseInt(s.replace(/^0+(\d)/, '$1'));
    }
</script>
Tom G
  • 3,650
  • 1
  • 20
  • 19
0
const now = new Date(); // create a new date object with the current time

// Here are some examples of what javascript provides:
console.log({
    now,
    toDateString: now.toDateString(),
    toISOString: now.toISOString(),
    toLocaleString: now.toLocaleString(),
    toLocaleDateString: now.toLocaleDateString(),
    toLocaleTimeString: now.toLocaleTimeString(),
    toUTCString: now.toUTCString(),
    toTimeString: now.toTimeString(),
})

This prints:

[LOG]: {
  "now": "2022-08-02T10:29:26.891Z",
  "toDateString": "Tue Aug 02 2022",
  "toISOString": "2022-08-02T10:29:26.891Z",
  "toLocaleString": "02/08/2022, 11:29:26",
  "toLocaleDateString": "02/08/2022",
  "toLocaleTimeString": "11:29:26",
  "toUTCString": "Tue, 02 Aug 2022 10:29:26 GMT",
  "toTimeString": "11:29:26 GMT+0100 (British Summer Time)"
} 

Alternatively, for more options, you can use something like moment. For example, I used it here to get a date into a UK readable date string:

import moment from "moment";

const now = new Date(); // create a new date object with the current time

const getTimeFormatted = (date: number) =>
  moment(date).format("DD/MM/yyyy hh:mm a");

console.log(getTimeFormatted(now)) // prints: 01/08/2022 11:29 am
JimmyTheCode
  • 3,783
  • 7
  • 29
  • 71