Chrome和Firefox浏览器执行new Date() 函数传参数得到不同结果的陷阱

时间:2023-03-19 11:03:43

某日,同事问到关于new Date() 函数传参数,在火狐浏览器和谷歌浏览器控制台运行,会得到不同的结果,刚开始觉得不可能,后来实际操作才发现此陷阱

var date = new Date('2014-07-25T23:00:00');
alert(date);

在火狐浏览器返回的是:

Date {Fri Jul 25 2014 23:00:00 GMT+0800}

火狐浏览器版本(通过navigator.userAgent输出):"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0"

在谷歌浏览器返回的是:

Sat Jul 26 2014 07:00:00 GMT+0800 (中国标准时间)

谷歌浏览器版本(通过navigator.userAgent输出):"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36"

两个时间对比,谷歌浏览器把传进的字符串当做是UTC时间,加上了8个小时(北京处于东八区),new Date()内部调用的是Date.parse('2014-07-25T23:00:00Z')函数

而火狐浏览器当做是本地时区没有自动加上,在火狐浏览器中传递UTC格式字符串最后加上Z(Z表示zulu time,就是格林威治时间)。

当然也可以在UTC字符串末尾加入一个零时区的offset“+00:00”,如‘2014-07-25T23:00:00+00:00’。

火狐浏览器运行结果如下:

new Date('2014-07-25T23:00:00');
Date {Fri Jul 25 2014 23:00:00 GMT+0800}
new Date('2014-07-25T23:00:00Z');
Date {Sat Jul 26 2014 07:00:00 GMT+0800}
new Date('2014-07-25T23:00:00+00:00');
Date {Sat Jul 26 2014 07:00:00 GMT+0800}

谷歌浏览器运行结果如下:

new Date('2014-07-25T23:00:00');
Sat Jul 26 2014 07:00:00 GMT+0800 (中国标准时间)
new Date('2014-07-25T23:00:00Z');
Sat Jul 26 2014 07:00:00 GMT+0800 (中国标准时间)
new Date('2014-07-25T23:00:00+00:00');
Sat Jul 26 2014 07:00:00 GMT+0800 (中国标准时间)

因为不知道浏览器加不加区时,所以建议是自己写一个函数实现将字符串转化为时间格式:

//将字符串转换为时间格式,适用各种浏览器,格式如2011-08-03 09:15:11
function GetTimeByTimeStr(dateString) {
var timeArr=dateStr.split(" ");
var d=timeArr[0].split("-");
var t=timeArr[1].split(":");
new Date(d[0],(d[1]-1),d[2],t[0],t[1],t[2]);
} //将时间转换为字符串格式,适用各种浏览器
function GetTimeStrByTime(time,stringType) {
var y = time.getFullYear();
var M = time.getMonth() + 1;
var d = time.getDate();
var h = time.getHours();
var m = date.getMinutes();
if(stringType==1)
return y + '-' + (M < 10 ? ('0' + M) : M) + '-' + (d < 10 ? ('0' + d) : d) + " " + (h < 10 ? ('0' + h) : h) + ":" + (m < 10 ? ('0' + m) : m);
return y + '/' + (M < 10 ? ('0' + M) : M) + '/' + (d < 10 ? ('0' + d) : d) + " " + (h < 10 ? ('0' + h) : h) + ":" + (m < 10 ? ('0' + m) : m);
}

另外,可以对常见的JSON格式数据进行扩展转换

//将json格式时间字符串规范化为正规字符串或者时间,如"\/Date(1406217600000)\/" 
function GetTimeStrByJsonStr(JsonStr) {
var date = new Date(parseInt(sonStr.replace("/Date(", "").replace(")/", ""), 10));
return GetTimeStrByTime(date,2);
}
//时间参数为“7月25日13时”
function getDateTimeStr(startDate,dateString) {
var currenthour = dateString.split('日')[1];
if (currenthour.indexOf("时") != -1)
currenthour = currenthour.split('时')[0];
if (currenthour == 0)
currenthour = 24;
var tempdate = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate());
tempdate.setTime(tempdate.getTime() + currenthour * 3600000);
return GetTimeStrByTime(tempdate, 2);
}