【发布时间】:2019-02-28 20:41:52
【问题描述】:
This answer 提供了一种在 JavaScript 中检查日期的好方法:
function isValidDate(d) {
return d instanceof Date && !isNaN(d);
}
但是,这在 Chrome 中对我不起作用,因为它将包含数字的字符串识别为日期:
function getDate(str) {
console.log(new Date(str).toLocaleString());
}
getDate("a string that contains the number 1");
getDate("a string that contains the number 12");
getDate("a string that contains the number 123");
getDate("a string that contains the number 1234");
getDate("a string that contains the number 12345");
getDate("a string that contains the number 123456");
getDate("a string that contains the number 1234567"); // in Chrome, only this one returns "Invalid Date"
实现更严格的日期检查器以配合 Chrome 灵活的日期解析的最佳方式是什么?我不能使用任何需要以特定方式格式化日期的东西(例如,只接受 ISO 8601 格式)。
【问题讨论】:
-
d instanceof Date不是检查日期的好方法,因为它会 fail across frames and documents 由于不同的执行上下文,请参阅 stackoverflow.com/a/1353711/257182 以获得更好的方法。 -
@RobG 很高兴了解窗口之间的
instanceof,谢谢。但是你作为重复链接的问题并不能真正解决我的问题。我知道new Date()和Date.parse是依赖于实现的,但我仍然需要一种方法来强制Chrome 更严格,而the top answer 在重复的问题上只是说“我建议手动解析日期字符串”,这在我的情况下不是一个选择。 -
如副本中所述,内置解析器依赖于实现。关于验证日期字符串有很多问题,也许How to validate a date?有你的答案。
标签: javascript google-chrome date parsing