Error parsing date string with `new Date`

后端 未结 1 1625
执念已碎
执念已碎 2020-12-12 05:33
datefromJSON = req.body.occasion_date;
occasion_date = new Date(datefromJSON);
console.log(occasion_date);

//while running this i get log like this 
//\"Invalid Dat         


        
相关标签:
1条回答
  • 2020-12-12 06:23

    Your date string (whatever it is "31-08-2016") isn't in a format recognized by the Date constructor. So you ended up with a Date whose underlying time value is NaN, which is shown as "Invalid Date" when you ask for the string version. Gratuitous example:

    console.log(new Date("foobar").toString());

    The only format the specification requires a JavaScript implementation to support is the one added in the ES5 specification in 2009, which was meant to be (and as of ES2015 actually is; there was an error in ES5) a subset of ISO-8601. So for instance:

    console.log(new Date("2016-08-31T09:25").toString());

    Every JavaScript implementation I've run into also unofficially supports parsing the U.S. format with slashes, MM/dd/yyyy, (even in non-U.S. locales), but the timezone varies (most interpret it as local time, others interpret it in GMT).

    So you'll need to either:

    • Parse your string (regular expressions, split, etc.) and use the form of the Date constructor that supports supplying the parts individually. Mind the gotcha that the months value starts with 0 = January (not 1 = January). There are several dozen questions with examples of that here on SO. Here's an example of parsing the common 'dd-MM-yyyy HH:mm:ss or 'dd-MM-yyyy HH:mm:ss.SSS format as a local date/time:

      Regex-based:

    function parseIt(str) {
      var rex = /^\s*(\d{1,2})[\/-](\d{1,2})[\/-](\d{4})(?: (\d{1,2})(?::(\d{1,2})(?::(\d{1,2})(?:\.(\d{1,3}))?)?)?)?\s*$/;
      var parts = rex.exec(str);
      var dt = null;
      if (parts) {
        dt = new Date(+parts[3], // Year
          +parts[2] - 1, // Month
          +parts[1], // Day
          +parts[4] || 0, // Hours
          +parts[5] || 0, // Minutes
          +parts[6] || 0, // Seconds
          +parts[7] || 0 // Milliseconds
        );
      }
      return dt;
    }
    
    function test(str) {
      var dt = parseIt(str);
      console.log(str, "=>");
      console.log("   " + String(dt));
      console.log("   (" + (dt ? dt.toISOString() : "null") + ")");
    }
    
    test("foobar");
    test("31-08-2016");
    test("31/08/2016");
    test("31/08/2016 9");
    test("31/08/2016 9:25");
    test("31/08/2016 09:25");
    test("31/08/2016 09:25:17");
    test("31/08/2016 09:25:17.342");

    The regex looks complicated, but it's really just a bunch of capture groups nested inside non-capturing, optional groups. Explanation here.

    • Use a library (like MomentJS) that lets you parse a string by saying what the format is.
    0 讨论(0)
提交回复
热议问题