Safari JS 无法解析 YYYY-MM-DD 日期格式? [英] Safari JS cannot parse YYYY-MM-DD date format?
问题描述
在我正在进行的项目中,我需要验证输入到 <input type="date">
In a project I am working on, I need to validate a date entered into an <input type="date">
使用 Safari 4/5(在 Mac OSX 上),Javascript 无法解析 YYYY-MM-DD
格式的日期,返回 NaN
而不是预期的纪元时间戳.
With Safari 4/5 (on Mac OSX) the Javascript fails to parse dates of the format YYYY-MM-DD
, returning NaN
instead of the expected epoch timestamp.
我正在使用以下技术在提交表单之前验证字段:
I am using the following technique to validate the field just before the form is submitted:
//value = '2010-06-21'
var stamp = Date.parse(value);
if (isNaN(stamp)) {
//notify user
} else {
value = new Date(stamp).format_mysql();
}
其中 format_mysql()
是一个原型函数,它将日期(正确地)格式化为 MySQL 日期时间格式(YYYY-MM-DD).
Where format_mysql()
is a prototype function that formats the date (correctly) into MySQL Date-Time format (YYYY-MM-DD).
用 /
的 (YYYY/MM/DD) 替换 -
会产生一个正确"的时间戳.
Replacing the -
's with /
's (YYYY/MM/DD) yields a "correct" timestamp.
我应该注意到该字段应该接受任何日期格式,而不仅仅是 YYYY-MM-DD,尽管我愿意,但我不能使用像 Date.js 这样的库
I should note that the field should accept any date format, not just YYYY-MM-DD, and that though I would like to, I cannot use libraries like Date.js
我该如何解决这个问题,或者是否有更好的方法来解析/验证日期?
推荐答案
Date.parse
方法依赖于实现,在 ECMAScript 5 上,此方法可以解析 ISO8601 格式的日期,但我建议您手动进行解析.
The behavior of the Date.parse
method is implementation dependent, on ECMAScript 5, this method can parse ISO8601 formatted dates, but I would recommend you to make the parsing manually.
前段时间我做了一个简单的函数,可以处理格式说明符参数:
Some time ago I've made a simple function, that can handle a format specifier argument:
function parseDate(input, format) {
format = format || 'yyyy-mm-dd'; // default format
var parts = input.match(/(d+)/g),
i = 0, fmt = {};
// extract date-part indexes from the format
format.replace(/(yyyy|dd|mm)/g, function(part) { fmt[part] = i++; });
return new Date(parts[fmt['yyyy']], parts[fmt['mm']]-1, parts[fmt['dd']]);
}
parseDate('06.21.2010', 'mm.dd.yyyy');
parseDate('21.06.2010', 'dd.mm.yyyy');
parseDate('2010/06/21', 'yyyy/mm/dd');
parseDate('2010-06-21');
您还可以检测 ECMAScript 5 行为来解析 ISO 格式的日期,您可以检查 Date.prototype.toISOString
是否可用,例如:
Also you could detect the ECMAScript 5 behavior to parse ISO formatted dates, you can check if the Date.prototype.toISOString
is available, e.g.:
if (typeof Date.prototype.toISOString == "function") {
// ES5 ISO date parsing available
}
这篇关于Safari JS 无法解析 YYYY-MM-DD 日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!