从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。

如何使用JavaScript或jQuery来做到这一点?


当前回答

function getUTC(str) {
    var arr = str.split(/[- :]/);
    var utc = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);
    utc.setTime(utc.getTime() - utc.getTimezoneOffset()*60*1000)
    return utc;
}

对于其他访问的人-使用此函数从UTC字符串中获取本地日期对象,应该关心DST,并将在IE, IPhone等上工作。

我们分割字符串(因为JS日期解析在某些浏览器上不支持) 我们得到UTC的差值,然后用UTC时间减去它,得到当地时间。由于返回的偏移量是用DST计算的(如果我错了请纠正我),所以它将在变量“utc”中设置该时间。最后返回date对象。

其他回答

在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

我在safari/chrome/firefox浏览器中使用这种方法效果很好:

const localDate = new Date(`${utcDate.replace(/-/g, '/')} UTC`);

对我来说,这很有效

if (typeof date === "number") {
  time = new Date(date).toLocaleString();
  } else if (typeof date === "string"){
  time = new Date(`${date} UTC`).toLocaleString();
}

这是一个普遍的解决方案:

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;   
}

用法:

var date = convertUTCDateToLocalDate(new Date(date_string_you_received));

根据客户端本地设置显示日期:

date.toLocaleString();
function getUTC(str) {
    var arr = str.split(/[- :]/);
    var utc = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);
    utc.setTime(utc.getTime() - utc.getTimezoneOffset()*60*1000)
    return utc;
}

对于其他访问的人-使用此函数从UTC字符串中获取本地日期对象,应该关心DST,并将在IE, IPhone等上工作。

我们分割字符串(因为JS日期解析在某些浏览器上不支持) 我们得到UTC的差值,然后用UTC时间减去它,得到当地时间。由于返回的偏移量是用DST计算的(如果我错了请纠正我),所以它将在变量“utc”中设置该时间。最后返回date对象。