欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

解决javaScript在不同时区new Date()显示值不同问题

程序员文章站 2022-03-20 17:47:32
在日期格式化时遇到的问题,日期格式化方法在最下面 如果在中国时区 formatDate('2019-07-09') 结果是 ‘2019-07-09’ 如果 在夏威夷时区 utc-10:00 或者别的时区 formatDate('2019-07-09') 结果是 ‘2019-07-08’ 时区不同导致 ......

在日期格式化时遇到的问题,日期格式化方法在最下面

如果在中国时区    formatdate('2019-07-09')  结果是 ‘2019-07-09’

如果 在夏威夷时区 utc-10:00 或者别的时区  formatdate('2019-07-09')  结果是 ‘2019-07-08’

时区不同导致日期格式化结果不同,查看代码发现不同时区 new date(str)的结果不同

 下面是浏览器测试例子

时区设置为北京 utc+08:00

var str = '2019-07-09';
var str1 = '2019-07-09 13:00:00';
console.log(new date(str));
console.log(new date(str1));
vm158:3 tue jul 09 2019 08:00:00 gmt+0800 (china standard time)
vm158:4 tue jul 09 2019 13:00:00 gmt+0800 (china standard time)

时区设置为夏威夷 utc-10:00 

var str = '2019-07-09';
var str1 = '2019-07-09 13:00:00';
console.log(new date(str));
console.log(new date(str1));
vm155:3 mon jul 08 2019 14:00:00 gmt-1000 (local standard time)
vm155:4 tue jul 09 2019 13:00:00 gmt-1000 (local standard time)

解决办法是在方法中添加如下代码

if (typeof str == 'string' && str.indexof(':') == -1) {
str += ' 00:00:00';
}


感觉解决办法不是太好,如果有更好的办法请大神告知,谢谢

 

 

//日期格式化方法

function formatdate(str, fmt) {
    if (!str) return '';
fmt = fmt || "yyyy-mm-dd"; //默认只显示年月日
if (this.getieversion() > -1) {
str = str.replace(/-/g, "/")
}
  //解决问题的代码
if (typeof str == 'string' && str.indexof(':') == -1) {
str += ' 00:00:00';
}
var date = new date(str);
var o = {
"m+": date.getmonth() + 1, //月
"d+": date.getdate(), //日
"h+": date.gethours() % 12 == 0 ? 12 : date.gethours() % 12, //时
"h+": date.gethours(), //小时
"m+": date.getminutes(), //分
"s+": date.getseconds(), //秒
"q+": math.floor((date.getmonth() + 3) / 3), //季
"s": date.getmilliseconds() //毫秒
},
week = {
"0": "\u65e5",
"1": "\u4e00",
"2": "\u4e8c",
"3": "\u4e09",
"4": "\u56db",
"5": "\u4e94",
"6": "\u516d"
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(regexp.$1, (date.getfullyear() + "").substr(4 - regexp.$1.length));
}
if (/(e+)/.test(fmt)) {
fmt = fmt.replace(regexp.$1, ((regexp.$1.length > 1) ? (regexp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[date.getday() + ""]);
}
for (var k in o) {
if (new regexp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(regexp.$1, (regexp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
}
return fmt;
},