【发布时间】:2009-07-31 18:55:46
【问题描述】:
我有一些 javascript 可以解析 ISO-8601 日期。出于某种原因,它在六月的日期失败了。但是七月和五月的日期工作正常,这对我来说没有意义。我希望新的眼光会有所帮助,因为我看不出我在这里做错了什么。
函数定义(有bug)
function parseISO8601(timestamp)
{
var regex = new RegExp("^([\\d]{4})-([\\d]{2})-([\\d]{2})T([\\d]{2}):([\\d]{2}):([\\d]{2})([\\+\\-])([\\d]{2}):([\\d]{2})$");
var matches = regex.exec(timestamp);
if(matches != null)
{
var offset = parseInt(matches[8], 10) * 60 + parseInt(matches[9], 10);
if(matches[7] == "-")
offset = -offset;
var date = new Date();
date.setUTCFullYear(parseInt(matches[1], 10));
date.setUTCMonth(parseInt(matches[2], 10) - 1); //UPDATE - this is wrong
date.setUTCDate(parseInt(matches[3], 10));
date.setUTCHours(parseInt(matches[4], 10));
date.setUTCMinutes(parseInt(matches[5], 10) - offset);
date.setUTCSeconds(parseInt(matches[6], 10));
date.setUTCMilliseconds(0);
return date;
}
return null;
}
测试代码
alert(parseISO8601('2009-05-09T12:30:00-00:00').toUTCString());
alert(parseISO8601('2009-06-09T12:30:00-00:00').toUTCString());
alert(parseISO8601('2009-07-09T12:30:00-00:00').toUTCString());
输出
- 格林威治标准时间 2009 年 5 月 9 日星期六 12:30:00
- 2009 年 7 月 9 日星期四 12:30:00 GMT
- 格林威治标准时间 2009 年 7 月 9 日星期四 12:30:00
更新
感谢快速解答,问题是Date对象最初是今天,恰好是7月31日。当月份设置为6月时,在我更改日期之前,暂时是6月31日,前滚至 7 月 1 日。
我发现以下是一个更简洁的实现,因为它一次设置所有日期属性:
function parseISO8601(timestamp)
{
var regex = new RegExp("^([\\d]{4})-([\\d]{2})-([\\d]{2})T([\\d]{2}):([\\d]{2}):([\\d]{2})([\\+\\-])([\\d]{2}):([\\d]{2})$");
var matches = regex.exec(timestamp);
if(matches != null)
{
var offset = parseInt(matches[8], 10) * 60 + parseInt(matches[9], 10);
if(matches[7] == "-")
offset = -offset;
return new Date(
Date.UTC(
parseInt(matches[1], 10),
parseInt(matches[2], 10) - 1,
parseInt(matches[3], 10),
parseInt(matches[4], 10),
parseInt(matches[5], 10),
parseInt(matches[6], 10)
) - offset*60*1000
);
}
return null;
}
【问题讨论】:
标签: javascript parsing date