【问题标题】:moment.js gives invalid date in firefox, but not in chromemoment.js 在 Firefox 中给出无效日期,但在 chrome 中没有
【发布时间】:2015-02-04 04:55:33
【问题描述】:

moment.js 有一个奇怪的问题。我编写了一个函数来将时间从 utc 转换为德国时间格式,并且在 chrome 中一切似乎都运行良好。但现在我用 Firefox 试了一下,发现日期无效。

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 );


}

   / ...

我已经看到了这个answer,但无论哪种方式都无法让它工作。有人可以帮帮我吗?

【问题讨论】:

    标签: javascript jquery google-chrome firefox momentjs


    【解决方案1】:

    从您的问题中不清楚代码的哪一部分引发了错误,但可能的罪魁祸首是 Moment.js 只是将非 ISO-8601 字符串委托给 Date.parsehttps://github.com/moment/moment/issues/1407

    因此,假设您使用 Moment 解析用户输入或未知格式的其他字段,或解析非 ISO-8601 格式,您将必须明确指定格式以保证交叉浏览器行为。否则,您将陷入跨浏览器 Date.parse 的模糊不清 - 唯一能始终如一地工作的格式是 ISO-8601。

    【讨论】:

    • 也可以直接从 datepicker 插件中获取日期对象,而不是使用输入值。 api.jqueryui.com/datepicker/#method-getDate
    • 这个答案是完美的解决方案。这节省了我大量时间来解决我的应用程序中的问题。
    【解决方案2】:
    moment(date_string, date_format);
    

    在解析您的日期时传递格式。示例

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

    【讨论】:

    • 是的,这就是解决方案。谢谢!
    猜你喜欢
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    相关资源
    最近更新 更多