我有一些JavaScript代码,用于解析ISO-8601日期格式。但是,它在六月份的日期上出现了问题。然而七月和五月份的日期却能正常工作,这让我感到困惑。希望您能帮忙找出问题所在,因为我无法看出我在这里做错了什么。
函数定义(带错误)
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 GMT
- 2009年7月9日星期四 12:30:00 GMT
- 2009年7月9日星期四 12:30:00 GMT
更新
感谢快速回答,问题在于日期对象最初是今天,即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;
}
new Date(0)
,那么是可以的(因为那是“1970-01-01T00:00:00-00:00”)。 - Kipnew Date(0)
也可以解决这个问题,因为没有意外的月末滚动风险。 - Grant Wagner