[英]Moment.js gives Invalid date in Firefox
I have a requirement to convert date time in moment.js.我需要在 moment.js 中转换日期时间。 But it gives me different result in Chrome and Firefox.
但它在 Chrome 和 Firefox 中给了我不同的结果。
In Google Chrome it gives correct result but in Mozilla firefox gives "Invalid date".在 Google Chrome 中,它给出了正确的结果,但在 Mozilla firefox 中给出了“无效日期”。
Google chrome谷歌浏览器
moment('2016-Jan-02 02:00 AM').format()
Output: "2016-01-02T02:00:00+05:30"
Mozilla firefox火狐浏览器
moment('2016-Jan-02 02:00 AM').format()
"Invalid date"
Your help is much appreciated.非常感谢您的帮助。
It's recommended to avoid using moment parsing with custom format.建议避免使用自定义格式的矩解析。 As the 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.
对于解析除 ISO 8601 字符串以外的任何内容的一致结果,您应该使用 String + Format。
In your case, the code for consistent parsing will be:在您的情况下,一致解析的代码将是:
moment('2016-Jan-02 02:00 AM', 'YYYY-MMM-DD HH:mm A')
You're not specifying a format for parsing the string 2016-Jan-02.您没有指定解析字符串 2016-Jan-02 的格式。 So moment falls back to the native Date object, which is inconsistent across the different browsers.
所以 moment 回退到本地 Date 对象,这在不同的浏览器中是不一致的。 To parse the date consistently, include a format string along with it.
要一致地解析日期,请包含格式字符串。
eg例如
moment("2016-Jan-02", "DD-MMM-YYYY")
Then if you want to format the moment object as a string, you can do what you were doing before:然后,如果您想将 moment 对象格式化为字符串,您可以执行之前的操作:
moment("2016-Jan-02", "DD-MMM-YYYY").format("DD-MM-YYYY")
which returns the string 02-01-2016 in both browsers.它在两个浏览器中都返回字符串 02-01-2016。
You need to specify input date format inside moment您需要在 moment 中指定输入日期格式
moment("input_date_string", "format_of_input_date_string").format("format_of_output_date_string")
eg:例如:
moment("27-06-2022", "DD-MM-YYYY").format("YYYY-MM-DD")
output: 2022-06-27输出:2022-06-27
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.