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

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


当前回答

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)

其他回答

对我来说,最简单的方法似乎很有用

datetime.setUTCHours(datetime.getHours());
datetime.setUTCMinutes(datetime.getMinutes());

(我认为第一行可以足够了,但有时区,在几个小时的分数)

如果有人想要显示转换后的时间到特定id元素的函数,并应用日期格式字符串yyyy-mm-dd 这里date1是字符串,ids是time要显示的元素id。

function convertUTCDateToLocalDate(date1, ids) 
{
  var newDate = new Date();
  var ary = date1.split(" ");
  var ary2 = ary[0].split("-");
  var ary1 = ary[1].split(":");
  var month_short = Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
  newDate.setUTCHours(parseInt(ary1[0]));
  newDate.setUTCMinutes(ary1[1]);
  newDate.setUTCSeconds(ary1[2]);
  newDate.setUTCFullYear(ary2[0]);
  newDate.setUTCMonth(ary2[1]);
  newDate.setUTCDate(ary2[2]);
  ids = document.getElementById(ids);
  ids.innerHTML = " " + newDate.getDate() + "-" + month_short[newDate.getMonth() - 1] + "-" + newDate.getFullYear() + " " + newDate.getHours() + ":" + newDate.getMinutes() + ":" + newDate.getSeconds();
            }

我知道这个答案已经被接受了,但我来到这里是因为谷歌,我确实从接受的答案中得到了灵感,所以如果有人需要,我确实想分享它。

在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`);

对我来说,上述解决方案并不奏效。

在IE中,UTC日期-时间到本地的转换有点棘手。 对我来说,来自web API的日期-时间是“2018-02-15T05:37:26.007”,我想按照当地时区进行转换,所以我使用了下面的JavaScript代码。

var createdDateTime = new Date('2018-02-15T05:37:26.007' + 'Z');