从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
当前回答
对我来说,上述解决方案并不奏效。
在IE中,UTC日期-时间到本地的转换有点棘手。 对我来说,来自web API的日期-时间是“2018-02-15T05:37:26.007”,我想按照当地时区进行转换,所以我使用了下面的JavaScript代码。
var createdDateTime = new Date('2018-02-15T05:37:26.007' + 'Z');
其他回答
在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
我创建了一个函数,将所有时区转换为本地时间。
我没有使用getTimezoneOffset(),因为它没有返回适当的偏移值
要求:
1. npm i moment-timezone
function utcToLocal(utcdateTime, tz) {
var zone = moment.tz(tz).format("Z") // Actual zone value e:g +5:30
var zoneValue = zone.replace(/[^0-9: ]/g, "") // Zone value without + - chars
var operator = zone && zone.split("") && zone.split("")[0] === "-" ? "-" : "+" // operator for addition subtraction
var localDateTime
var hours = zoneValue.split(":")[0]
var minutes = zoneValue.split(":")[1]
if (operator === "-") {
localDateTime = moment(utcdateTime).subtract(hours, "hours").subtract(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
} else if (operator) {
localDateTime = moment(utcdateTime).add(hours, "hours").add(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
} else {
localDateTime = "Invalid Timezone Operator"
}
return localDateTime
}
utcToLocal("2019-11-14 07:15:37", "Asia/Kolkata")
//Returns "2019-11-14 12:45:37"
这对我来说很管用:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime() - date.getTimezoneOffset()*60*1000);
return newDate;
}
Matt的回答忽略了一个事实,即Date()和它需要转换的日期时间之间的夏令时可能不同-这是我的解决方案:
function ConvertUTCTimeToLocalTime(UTCDateString)
{
var convertdLocalTime = new Date(UTCDateString);
var hourOffset = convertdLocalTime.getTimezoneOffset() / 60;
convertdLocalTime.setHours( convertdLocalTime.getHours() + hourOffset );
return convertdLocalTime;
}
调试器中的结果:
UTCDateString: "2014-02-26T00:00:00"
convertdLocalTime: Wed Feb 26 2014 00:00:00 GMT-0800 (Pacific Standard Time)
你可以使用moment.js文件来完成。
很简单,你只是提到了时区的位置。
示例:如果你要将你的datetime转换为亚洲/加尔各答时区,你必须只提到从moment.js中获得的时区地点的名称
var UTCDateTime="从UTC获得的日期"; var ISTleadTime =(时刻。tz (UTCDateTime,“非洲/阿比让”)).tz(“亚洲/加尔各答”)。格式(YYYY-MM-DD LT);