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格式)。
发布于 2019-03-01 05:05:14
如果不控制格式,您将很难解析它,并且您可能会得到错误的数据。例如,在许多其他国家,月份和日期是互换的。所以如果你的日期是11/11,你不知道哪个是月份。
也就是说,我将使用一个库,而不是尝试重新发明日期解析的轮子。Moment.js非常好,它会告诉您日期字符串是否有效:https://momentjs.com/docs/#/parsing/string/
https://stackoverflow.com/questions/54933944
复制相似问题