从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
当前回答
在Angular中,我这样使用Ben的回答:
$scope.convert = function (thedate) {
var tempstr = thedate.toString();
var newstr = tempstr.toString().replace(/GMT.*/g, "");
newstr = newstr + " UTC";
return new Date(newstr);
};
编辑:Angular 1.3.0添加了UTC日期过滤器,我还没有使用过,但它应该更简单,格式如下:
{{ date_expression | date : format : timezone}}
Angular 1.4.3 Date API
其他回答
tl;dr (new Date('6/29/2011 4:52:48 PM UTC')).toString()
源字符串必须指定时区或UTC。
一行程序:
(new Date('6/29/2011 4:52:48 PM UTC')).toString()
结果在我的一个web浏览器:
"Wed Jun 29 2011 09:52:48 GMT-0700 (Pacific Daylight Time)"
这种方法甚至适当地选择标准/日光时间。
(new Date('1/29/2011 4:52:48 PM UTC')).toString()
结果在我的浏览器:
"Sat Jan 29 2011 08:52:48 GMT-0800 (Pacific Standard Time)"
在最后添加时区,在本例中是'UTC':
theDate = new Date( Date.parse('6/29/2011 4:52:48 PM UTC'));
之后,使用toLocale()*函数族以正确的地区显示日期
theDate.toLocaleString(); // "6/29/2011, 9:52:48 AM"
theDate.toLocaleTimeString(); // "9:52:48 AM"
theDate.toLocaleDateString(); // "6/29/2011"
UTC到本地到ISO -使用Molp Burnbright回答
因为服务器只接受ISO日期-时间,所以我将UTC转换为我的本地时区,并以ISO格式发送给服务器
在某处声明
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime() - date.getTimezoneOffset()*60*1000);
return newDate;
}
并在需要ISO格式的本地日期时间时执行此操作。
在JavaScript中,我使用:
var updaated_time= "2022-10-25T06:47:42.000Z"
{{updaated_time | date: 'dd-MM-yyyy HH:mm'}} //output: 26-10-2022 12:00
对我来说,这很有效
if (typeof date === "number") {
time = new Date(date).toLocaleString();
} else if (typeof date === "string"){
time = new Date(`${date} UTC`).toLocaleString();
}