JavaScript Date ISO8601

后端 未结 3 1615
刺人心
刺人心 2021-02-02 12:30

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

3条回答
  •  無奈伤痛
    2021-02-02 13:00

    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);
    

提交回复
热议问题