Date went wrong when using Momentjs date format in IE 11

三世轮回 提交于 2020-07-10 07:43:08

问题


I am using Moment.js format function on a current date as

var startDate = moment(new Date()).format('MM/DD/YY');

The result is 06/28/20

What happens is that it retains only the year part: 20 as "06/28/20", after I used new Date(startDate), the result is "Mon Jun 28 1920 00:00:00 GMT+0530 (India Standard Time)".

After this when I applied another format on "06/28/20":

startDate = moment(startDate ).format('MM-DD-YYYY');

The result is 06-28-1920

In Google Chrome and Firefox it gives the correct date for the second attempt as: 06-28-2020.

My code is:

$(document).ready(function() {

var startDate = moment(new Date()).format('MM/DD/YY');
alert("startDate ==="+startDate +"==="+new Date(startDate ));

startDate = moment(startDate ).format('MM-DD-YYYY');
alert("startDate ==="+startDate +"==="+new Date(startDate ));

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>

回答1:


Please find the below snippet , which might help you

$(document).ready(function() {

  var startDate = moment(new Date()).format('MM/DD/YY');
  alert("startDate ==="+startDate +"==="+new Date(startDate ));
  
  startDate = moment(new Date(startDate)).format('MM-DD-YYYY');
  var str="06-28-2020";
  
  
  alert("startDate ==="+startDate +"==="+new Date(str.replaceAll("-","/")));
  
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>



回答2:


If you are using Moment, use Moment only. Parsing date strings with Date.parse() or new Date() (same thing under hood) is not recommended.

Your approach should be using moment(DATE, "DD/MM/YY") which handles the 2k year problem you face, automatically.



来源:https://stackoverflow.com/questions/62622534/date-went-wrong-when-using-momentjs-date-format-in-ie-11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!