Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Date ISO8601

What is the best way to get a Javascript Date object from a string like the following one:

2011-06-02T09:34:29+02:00 ?

I have trouble with the time zone part (obviously).

like image 831
Luc Avatar asked Jun 03 '11 14:06

Luc


3 Answers

var myDate = new Date('2011-06-02T09:34:29+02:00');
alert(myDate);
like image 164
Jason McCreary Avatar answered Nov 17 '22 11:11

Jason McCreary


IE 8 and below, and older versions of the other browsers do not implement the ISO Date format. A problem is that some of the browsers do return a date, instead of NaN, just not the correct one.

You can write your own method, if you want to support them. The time zone is the tricky bit.

This example will run once and set a Date.fromISO method- if the native method is supported it will use it.

(function(){
var D= new Date('2011-06-02T09:34:29+02:00');
if(isNaN(D) || D.getUTCMonth()!== 5 || D.getUTCDate()!== 2 ||
D.getUTCHours()!== 7 || D.getUTCMinutes()!== 34){
    Date.fromISO= function(s){
        var day, tz,
        rx=/^(\d{4}\-\d\d\-\d\d([tT][\d:\.]*)?)([zZ]|([+\-])(\d\d):(\d\d))?$/,
        p= rx.exec(s) || [];
        if(p[1]){
            day= p[1].split(/\D/);
            for(var i= 0, L= day.length; i<L; i++){
                day[i]= parseInt(day[i], 10) || 0;
            }
            day[1]-= 1;
            day= new Date(Date.UTC.apply(Date, day));
            if(!day.getDate()) return NaN;
            if(p[5]){
                tz= (parseInt(p[5], 10)*60);
                if(p[6]) tz+= parseInt(p[6], 10);
                if(p[4]== '+') tz*= -1;
                if(tz) day.setUTCMinutes(day.getUTCMinutes()+ tz);
            }
            return day;
        }
        return NaN;
    }
    // remove test:
    alert('ISO Date Not correctly implemented');
}
else{
    Date.fromISO= function(s){
        return new Date(s);
    }
    // remove test:
    alert('ISO Date implemented');
}
})()


// remove test
var D=Date.fromISO('2011-06-02T09:34:29+02:00');
alert(D.toUTCString())
like image 33
kennebec Avatar answered Nov 17 '22 11:11

kennebec


If your string is an ISO8601 string, you can just pass it into the Date constructor and get a Date object back out:

var date = new Date('2011-06-02T09:34:29+02:00');

According to http://dev.enekoalonso.com/2010/09/21/date-from-iso-8601-string/ though, this might have issues in IE and other platforms. It recommends you do something like this for compatibility:

function dateFromISO8601(isostr) {
    var parts = isostr.match(/\d+/g);
    return new Date(parts[0], parts[1] – 1, parts[2], parts[3], parts[4], parts[5]);
}

var myDate = dateFromISO8601("2011-06-02T09:34:29+02:00");
console.log(myDate);
like image 5
Eli Avatar answered Nov 17 '22 12:11

Eli