【问题标题】:A stricter way of checking for dates in Chrome [duplicate]在 Chrome 中检查日期的更严格方法 [重复]
【发布时间】: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


【解决方案1】:

如果不控制格式,您将很难解析它,并且您可能会得到错误的数据。例如,在许多其他国家/地区,月份和日期是互换的。因此,如果您的日期是 11 月 11 日,则您不知道是哪一个月。

话虽如此,我会使用库而不是尝试重新发明日期解析的轮子。 Moment.js 很不错,它会告诉你它是否认为日期字符串是有效的:https://momentjs.com/docs/#/parsing/string/

【讨论】:

  • Moment.js 的行为方式相同,除非明确指定一种格式。但是关于 11/11 的观点非常好。可能没有任何方法可以做我要求的事情。 :-/
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-03
  • 1970-01-01
  • 2017-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-30
相关资源
最近更新 更多