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
如何解决这个问题,还是有更好的方法来解析/验证日期?
推荐答案
日期的行为.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屋!