moment.js gives invalid date in firefox, but not in chrome

此生再无相见时 提交于 2021-01-27 05:27:38

问题


I'm having a strange issue with moment.js. I wrote a function to convert the time from utc to german time format, and everything seemed to work just fine in chrome. But now I tried it with firefox and here I got an invalid date.

moment.locale("de");

$('#from').datepicker({
    format: "DD. MMMM YYYY"
});

$('#from').on('change',function() {

    var a = moment($('#from').val(), "DD. MMMM YYYY").format("LLLL");
    var b = moment(a).add(7,'days');


    var localTime  = moment.utc(b).toDate();
    localTime = moment(localTime).format('DD. MMMM YYYY');


    $('#to').val(localTime);

});



$('#to').datepicker({
    format:'DD.MMMM YYYY'
});



$('#sendbtn').on('click',function(){

    /...

    var from = moment(fromfield.value).format();

    var to = moment(tofield.value).format();


    /...

    $('#calendar').fullCalendar( 'gotoDate', from );
    getEventDate(from,to,persons.value);


    }

});

 function getEventDate(start,end,people) {

     var Calendar = $('#calendar');
     Calendar.fullCalendar();
     var Event = {
       title:"Your stay for "+people+" people",
       allDay: true,
       start: start,
       end: end

     };
      filljson(start,end,people);

      Calendar.fullCalendar( 'renderEvent', Event );


}

   / ...

I've seen this answer but can't get it to work either way. Can someone help me out?


回答1:


It's not clear from your question which part of the code is throwing the error, but the likely culprit is that Moment.js simply delegates to Date.parse for non-ISO-8601 strings: https://github.com/moment/moment/issues/1407

So assuming that you're using Moment to parse user input or another field in an unknown format, or to parse a format that's not ISO-8601, you're going to have to specify the format explicitly to get guaranteed cross-browser behavior. Otherwise you're diving into the vaguaries of cross-browser Date.parse - the only format that works consistently there is ISO-8601.




回答2:


moment(date_string, date_format);

Pass the format while parsing you date with moment. Example

moment("25/12/1995", "DD/MM/YYYY");


来源:https://stackoverflow.com/questions/27325750/moment-js-gives-invalid-date-in-firefox-but-not-in-chrome

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