【问题标题】:Date.parse behaving differently in FF and ChromeDate.parse 在 FF 和 Chrome 中的行为不同
【发布时间】:2015-11-17 11:57:05
【问题描述】:

我有一个 jquery datepicker 分配给一个文本字段。文本字段是不可编辑的,只有退格键可以用于删除日期。我已使用以下代码检查该字段是否具有有效日期。这在 mozilla 中非常有效,但在 chrome 中却不行。

<input type="text" class="date_field from_date" name="from_date" placeholder="From date">

//datepicker
$(".from_date").datepicker({
    dateFormat: "yy-mm-dd"
});
//only backspace keypress allowed
$(".date_field").keydown(function (e) {
    if (e.keyCode != 8) {
        e.preventDefault();
    }

});

//check the date is valid.
//For example('2015-09-' is the value of textfield)
alert(Date.parse($('.from_date').val()));
//returns NaN in mozilla,but returns number in chrome
if (Date.parse($('.from_date').val())) {
    //do the rest code
}

【问题讨论】:

  • 是否返回NaN
  • @WisdmLabs mozilla 返回 NaN,但 chrome 给了我一个数字
  • Date.parse 在 chrome 上运行良好,它在您的情况下返回与“2015-09-01”相同的数字。 Date.parse 不是测试日期格式是否正确的最佳方法。您必须使用一些正则表达式来匹配您想要的日期模式。我建议 T.J.Crowder 先检查 dateString.test(/^\d{4}-\d{2}-\d{2}$/) 然后测试 Date.parse 是否不返回 NaN
  • 由于Date.parse 不是为了测试字符串是否代表有效日期,而是尝试从给定字符串中获取日期,我会说这实际上不是“@987654328”的情况@ 不在 Chrome 中工作”,而是“Date.parse 在 FF 和 Chrome 中的行为不同”的情况。我想这个问题的标题应该改写以反映这一点。

标签: jquery google-chrome date mozilla


【解决方案1】:

来自the spec

根据字符串的内容,字符串可能被解释为本地时间、UTC 时间或其他时区的时间。该函数首先尝试根据日期时间字符串格式 (20.3.1.16) 中调用的规则(包括延长年份)解析字符串的格式。 如果字符串不符合该格式,则函数可能会退回到任何特定于实施的启发式或特定于实施的日期格式。

(我的重点)

在这种情况下,Chrome 采用了缺失日期等于该月的第一天的启发式算法,因此它将“2015-09-”识别为 9 月的第一天。它还做了一些其他有趣的事情,比如将“2015-09-31”视为 10 月 1 日。 (这在很大程度上与 JavaScript 的 Date 自动处理翻转的方式保持一致。)

如果您想验证格式,您必须使用不会尝试应用特定于实现的启发式方法来执行此操作。例如:

if (dateString.test(/^\d{4}-\d{2}-\d{2}$/) {
    // It's in ####-##-## format. Still may not be valid, you can do more checking if necessary
}

【讨论】:

    猜你喜欢
    • 2011-11-05
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 2012-12-10
    • 2011-08-23
    • 2018-01-06
    • 2011-10-21
    • 1970-01-01
    相关资源
    最近更新 更多