Strange behavior in Javascript new Date function

前端 未结 2 1728
情书的邮戳
情书的邮戳 2020-12-10 02:55

I tried to make Date object from string in javascript, but i see javascript parse date string very strange here.

> new Date(\"2012-01-01\");
Sun Jan 01 20         


        
2条回答
  •  没有蜡笔的小新
    2020-12-10 03:37

    The reason for the difference is explained in other answers. A good way to avoid the issue is to parse the string yoruself. If you want 2012-01-01 to be treated as UTC then:

    function dateFromUTCString(s) {
      var s = s.split(/\D/);
      return new Date(Date.UTC(s[0], --s[1], s[2]));
    }
    

    If you want to treat it as a local date, then:

    function dateFromString(s) {
      var s = s.split(/\D/);
      return new Date(s[0], --s[1], s[2]);
    }
    

提交回复
热议问题