date() function returning Invalid Date in Safari and Firefox

前端 未结 5 1390
清酒与你
清酒与你 2021-02-14 03:57

I am formatting a date in the following way:

date = new Date(\"2013-05-12 20:00:00\");
formattedDate = new Date(date.getFullYear(),date.getMonth(),date.getDate()         


        
5条回答
  •  花落未央
    2021-02-14 04:48

    While the value 2013-05-12 20:00:00 is one several valid formats specified by ISO8601, it is best to use the profile defined in RFC3339, which is a sub-set of ISO8601.

    This means that you should have both the T separator, and a time zone offset - which can be numeric or Z to specify UTC. In other words, you should use a value like 2013-05-12T20:00:00-07:00, or the equivalent 2013-05-13T03:00:00Z.

    Now whether you have a correctly formatted input value or not, then the issue of browser compatibility comes up. All modern browsers support ISO8601, but some interpret it differently. For example, in Google Chrome, if you omit the T it is parsed as local time even if there is a Z at the end. In Internet Explorer, the same value with the T omitted returns an invalid date error.

    A better approach is to use a library that abstracts these differences away, so you can focus on your application and not the quirks of the browser. The best library I know of for this is moment.js. In addition to full support for ISO dates, you can parse input in any way that you want with custom format strings. It has lots of other features as well. I highly encourage you to take a look.

    Using moment.js, you can do the following:

    // from a full date-time-offset ISO8601/RFC3339 value
    var m = moment('2013-05-12T20:00:00-07:00');
    
    // or from your custom value, with explicit formatting
    // this will assume the local time zone because you didn't specify one
    var m = moment('2013-05-12 20:00:00','YYYY-MM-DD HH:mm:ss');
    
    // then you can output it in a custom format if you like
    m.format("ffffdd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, May 12th 2013, 8:00:00 pm"
    

    As far as I know, moment.js works in all browsers - including older ones like IE6.

提交回复
热议问题