Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 669
baao Avatar asked Dec 05 '14 22:12

baao


2 Answers

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.

like image 193
nrabinowitz Avatar answered Nov 17 '22 18:11

nrabinowitz


moment(date_string, date_format);

Pass the format while parsing you date with moment. Example

moment("25/12/1995", "DD/MM/YYYY");
like image 33
Robin Avatar answered Nov 17 '22 19:11

Robin