从服务器我得到一个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
其他回答
我创建了一个函数,将所有时区转换为本地时间。
我没有使用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"
@Adorojan的回答几乎是正确的。但是添加偏移量是不正确的,因为如果浏览器日期在GMT之前,偏移量值将为负,反之亦然。 下面是我的解决方案,对我来说是完美的:
// Input time in UTC var inputInUtc = "6/29/2011 4:52:48"; var dateInUtc = new Date(Date.parse(inputInUtc+" UTC")); //Print date in UTC time document.write("Date in UTC : " + dateInUtc.toISOString()+"<br>"); var dateInLocalTz = convertUtcToLocalTz(dateInUtc); //Print date in local time document.write("Date in Local : " + dateInLocalTz.toISOString()); function convertUtcToLocalTz(dateInUtc) { //Convert to local timezone return new Date(dateInUtc.getTime() - dateInUtc.getTimezoneOffset()*60*1000); }
对于TypeScript用户,这里有一个helper函数:
// Typescript Type: Date Options
interface DateOptions {
day: 'numeric' | 'short' | 'long',
month: 'numeric',
year: 'numeric',
timeZone: 'UTC',
};
// Helper Function: Convert UTC Date To Local Date
export const convertUTCDateToLocalDate = (date: Date) => {
// Date Options
const dateOptions: DateOptions = {
day: 'numeric',
month: 'numeric',
year: 'numeric',
timeZone: 'UTC',
};
// Formatted Date (4/20/2020)
const formattedDate = new Date(date.getTime() - date.getTimezoneOffset() * 60 * 1000).toLocaleString('en-US', dateOptions);
return formattedDate;
};
在我的例子中,我必须在几秒钟内找出日期的差异。日期是UTC日期字符串,因此我将其转换为本地日期对象。这就是我所做的:
let utc1 = new Date();
let utc2 = null;
const dateForCompare = new Date(valueFromServer);
dateForCompare.setTime(dateForCompare.getTime() - dateForCompare.getTimezoneOffset() *
60000);
utc2 = dateForCompare;
const seconds = Math.floor(utc1 - utc2) / 1000;
我写了一个漂亮的小脚本,它采用UTC纪元并将其转换为客户端系统时区,并以d/m/Y H: I:s(类似于PHP date函数)格式返回:
getTimezoneDate = function ( e ) {
function p(s) { return (s < 10) ? '0' + s : s; }
var t = new Date(0);
t.setUTCSeconds(e);
var d = p(t.getDate()),
m = p(t.getMonth()+1),
Y = p(t.getFullYear()),
H = p(t.getHours()),
i = p(t.getMinutes()),
s = p(t.getSeconds());
d = [d, m, Y].join('/') + ' ' + [H, i, s].join(':');
return d;
};