在 JavaScript 中创建新的 Date(string) 时,我一直在处理这个烦人的错误。我的问题是,有没有人为这个问题找到适用于大多数浏览器的更好/更标准化的解决方案?例如,我发现 IE9 不喜欢 .sss(毫秒),然后 Firefox 无法正确使用欧洲日期格式 (DD-MM-YYYY)。
让我知道你的想法!
最佳答案
根据 MDN:
Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
这同样适用于 Date.parse()
。如果您害怕这种不一致(因为您的浏览器支持非常广泛,或者因为您处理来自外部源的数据),您总是可以使用完整的构造函数:
new Date(year, month, [day, hour, minute, second, millisecond])
括号之间的参数是可选的。如果您可以使用可靠的工具(例如 moment.js
,正如您提到的)解析日期,那么您可以构建一个原生的 Date
,而不会使用它。
很麻烦,不过打包成一个函数,以后再也不用看了。
关于JavaScript new Date(string) 兼容大多数浏览器(2016 年 12 月),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41123180/