我有以下代码:
function parseDate(s) {
var date = new Date(s);
if (!isValidDate(date)) {
//iso 860 date parser, as some browsers do not support this via new Date yet
var re=/(\d\d\d\d)\D?(\d\d)\D?(\d\d)\D?(\d\d)\D?(\d\d\D?(\d\d\.?(\d*))?)(Z|[+-]\d\d?(:\d\d)?)?/;
var a=re(s).slice(1).map(function(x,i){
if (i==6 && x) x=parseInt(x,10)/Math.pow(10,x.length)*1000; // convert to milliseconds
return parseInt(x,10)||0;
});
date = new Date(Date.UTC(a[0],a[1]-1,a[2],a[3]-(a[7]||0),a[4],a[5],a[6]));
}
return date;
};
function isValidDate(d) {
if ( Object.prototype.toString.call(d) !== "[object Date]" )
return false;
return !isNaN(d.getTime());
}
这适用于除IE6-9之外的所有浏览器。我收到错误:
SCRIPT5002:预期的功能
它指向这一行:
var a=re(s).slice(1).map(function(x,i){
任何人都知道这有什么问题以及如何解决?
谢谢, 韦斯利
编辑:
如果我将代码更改为:
function parseDate(s) {
var date = new Date(s);
if (!isValidDate(date)) {
//iso 860 date parser, as some browsers do not support this via new Date yet
var re=/(\d\d\d\d)\D?(\d\d)\D?(\d\d)\D?(\d\d)\D?(\d\d\D?(\d\d\.?(\d*))?)(Z|[+-]\d\d?(:\d\d)?)?/;
var a = re.exec(s);
if (a) {
a = a.slice(1);
a.map(function(x,i){
if (i==6 && x) x=parseInt(x,10)/Math.pow(10,x.length)*1000; // convert to milliseconds
return parseInt(x,10)||0;
});
document.getElementById('test1').innerHTML = (a[0] + ' ' + a[1] + ' ' + a[2] + ' ' + a[3] + ' ' + a[4] + ' ' + a[5] + ' ' + a[6] + ' ' + a[7]);
date = new Date(Date.UTC(a[0],a[1]-1,a[2],a[3]-(a[7]||0),a[4],a[5],a[6]));
}
}
return date;
};
它仍然不起作用(在IE中抱怨.map)但有趣的是在safari(也许还有其他浏览器)中也不起作用。有什么理由吗?
你会注意到输出(来自新函数的document.write是:
2008 11 01 20 39:57.78 57.78 78 -06:00
来自旧功能:
2008 11 1 20 39 57 780 -6
答案 0 :(得分:4)
根据regular-expressions.info,您应该使用re.exec(s)
而不是re(s)
。该页面还提到re.test(s)
,但只返回true或false,re.exec(s)
实际返回匹配,这似乎是您想要的。
答案 1 :(得分:2)
.map
.map()
数组方法是ECMAScript 5提供的新增功能之一; JavaScript的最新官方版本(5.0截至2009年12月,现在5.1截至2011年6月)。很少(如果有的话)浏览器完全支持版本5(当然不是IE6)。您可以打赌,您可以依赖浏览器来支持所有新功能(例如Array.map()
)。
不幸的是,JavaScript不允许使用自由间隔模式指定正则表达式。这使得诸如此类的长期正则表达式难以阅读。为了解释你的算法不起作用的原因,我已经为你的正则表达式添加了注释,这些注释表明了捕获组真正捕获的内容。这是PHP语法:
$re_iso8601_date_needs_work = '%# Original Date regex
(\d\d\d\d)\D? # $1: Year.
(\d\d)\D? # $2: Month.
(\d\d)\D? # $3: Day.
(\d\d)\D? # $4: Hour.
( # $5: Minute and second. ???
\d\d\D? # Minute.
( # $6: Optional second.
\d\d\.? # Second (whole portion).
(\d*) # $7: Second (fractional portion).
)? # Second is optional.
) # End $5: minute and second.
( # $8: Optional timezone alternatives.
Z # Either UTC/Zulu.
| [+-]\d\d? # Or offset from UTC. Hours and
(:\d\d)? # $9: optional minutes.
)? # Timezone is optional.%x';
提示:小数秒位于$7
而不是$6
。为什么要在组$5
中捕获分钟和秒?
希望这有帮助! :)