Moment.js 在 Firefox 中给出无效日期
Moment.js gives Invalid date in Firefox
我需要转换 moment.js 中的日期时间。但它在 Chrome 和 Firefox 中给了我不同的结果。
在 Google Chrome 中给出正确的结果,但在 Mozilla firefox 中给出 "Invalid date"。
Google chrome
moment('2016-Jan-02 02:00 AM').format()
Output: "2016-01-02T02:00:00+05:30"
Mozilla 火狐
moment('2016-Jan-02 02:00 AM').format()
"Invalid date"
非常感谢您的帮助。
建议避免使用自定义格式的矩解析。作为 documentation states:
Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.
For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.
在您的情况下,一致解析的代码将是:
moment('2016-Jan-02 02:00 AM', 'YYYY-MMM-DD HH:mm A')
您没有指定用于解析字符串 2016-Jan-02 的格式。所以时刻回落到本机 Date 对象,这在不同的浏览器中是不一致的。要一致地解析日期,请在其中包含一个格式字符串。
例如
moment("2016-Jan-02", "DD-MMM-YYYY")
然后如果你想将 moment 对象格式化为字符串,你可以像之前那样做:
moment("2016-Jan-02", "DD-MMM-YYYY").format("DD-MM-YYYY")
其中 returns 两个浏览器中的字符串 02-01-2016。
我需要转换 moment.js 中的日期时间。但它在 Chrome 和 Firefox 中给了我不同的结果。
在 Google Chrome 中给出正确的结果,但在 Mozilla firefox 中给出 "Invalid date"。
Google chrome
moment('2016-Jan-02 02:00 AM').format()
Output: "2016-01-02T02:00:00+05:30"
Mozilla 火狐
moment('2016-Jan-02 02:00 AM').format()
"Invalid date"
非常感谢您的帮助。
建议避免使用自定义格式的矩解析。作为 documentation states:
Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.
For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.
在您的情况下,一致解析的代码将是:
moment('2016-Jan-02 02:00 AM', 'YYYY-MMM-DD HH:mm A')
您没有指定用于解析字符串 2016-Jan-02 的格式。所以时刻回落到本机 Date 对象,这在不同的浏览器中是不一致的。要一致地解析日期,请在其中包含一个格式字符串。
例如
moment("2016-Jan-02", "DD-MMM-YYYY")
然后如果你想将 moment 对象格式化为字符串,你可以像之前那样做:
moment("2016-Jan-02", "DD-MMM-YYYY").format("DD-MM-YYYY")
其中 returns 两个浏览器中的字符串 02-01-2016。