How to parse a date in format “YYYYmmdd” in JavaScript?

后端 未结 5 1293
自闭症患者
自闭症患者 2020-11-27 21:55

This is a noob question:

How to parse a date in format \"YYYYmmdd\" without external libraries ? If the input string is not in this format I would like

5条回答
  •  星月不相逢
    2020-11-27 22:43

    Example using only the digits in the string:

    function toDate(str) {
      var m = str.split(/\D/);
      return new Date(+m[0], +m[1] - 1, +m[2], +m[3], +m[4], +m[5]);
    }
        
    console.log(toDate("2020-08-23 23:34:45"));

提交回复
热议问题