本文翻译自:Convert UTC date time to local date time
From the server I get a datetime variable in this format: 6/29/2011 4:52:48 PM
and it is in UTC time. 从服务器上,我得到一个datetime变量,格式为: 6/29/2011 4:52:48 PM
,它是UTC时间。 I want to convert it to the current user's browser time using JavaScript. 我想使用JavaScript将其转换为当前用户的浏览器时间。
How this can be done using JavaScript or jQuery? 如何使用JavaScript或jQuery完成此操作?
#1楼
参考:https://stackoom.com/question/RNac/将UTC日期时间转换为本地日期时间
#2楼
To me the simplest seemed using 对我来说,最简单的方法似乎是使用
datetime.setUTCHours(datetime.getHours());
datetime.setUTCMinutes(datetime.getMinutes());
(i thought the first line could be enough but there are timezones which are off in fractions of hours) (我以为第一行可能就够了,但是有些时区会在几分之一小时内消失)
#3楼
This is an universal solution: 这是一个通用的解决方案:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
Usage: 用法:
var date = convertUTCDateToLocalDate(new Date(date_string_you_received));
Display the date based on the client local setting: 根据客户端本地设置显示日期:
date.toLocaleString();
#4楼
Use this for UTC and Local time convert and vice versa. 将其用于UTC和本地时间转换,反之亦然。
//Covert datetime by GMT offset
//If toUTC is true then return UTC time other wise return local time
function convertLocalDateToUTCDate(date, toUTC) {
date = new Date(date);
//Local time converted to UTC
console.log("Time: " + date);
var localOffset = date.getTimezoneOffset() * 60000;
var localTime = date.getTime();
if (toUTC) {
date = localTime + localOffset;
} else {
date = localTime - localOffset;
}
date = new Date(date);
console.log("Converted time: " + date);
return date;
}
#5楼
Matt's answer is missing the fact that the daylight savings time could be different between Date() and the date time it needs to convert - here is my solution: Matt的答案缺少以下事实:Date()和它需要转换的日期时间之间的夏令时可能有所不同-这是我的解决方案:
function ConvertUTCTimeToLocalTime(UTCDateString)
{
var convertdLocalTime = new Date(UTCDateString);
var hourOffset = convertdLocalTime.getTimezoneOffset() / 60;
convertdLocalTime.setHours( convertdLocalTime.getHours() + hourOffset );
return convertdLocalTime;
}
And the results in the debugger: 并将结果放入调试器:
UTCDateString: "2014-02-26T00:00:00"
convertdLocalTime: Wed Feb 26 2014 00:00:00 GMT-0800 (Pacific Standard Time)
#6楼
In Angular I used Ben's answer this way: 在Angular中,我这样使用Ben的答案:
$scope.convert = function (thedate) {
var tempstr = thedate.toString();
var newstr = tempstr.toString().replace(/GMT.*/g, "");
newstr = newstr + " UTC";
return new Date(newstr);
};
Edit: Angular 1.3.0 added UTC support to date filter, I haven't use it yet but it should be easier, here is the format: 编辑:Angular 1.3.0在日期过滤器中添加了UTC支持,我还没有使用它,但是它应该更容易一些,格式如下:
{{ date_expression | date : format : timezone}}