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

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


当前回答

根据@digitalbath的答案,下面是一个小函数,用于获取UTC时间戳,并在给定的DOM元素中显示本地时间(最后一部分使用jQuery):

https://jsfiddle.net/moriz/6ktb4sv8/1/

<div id="eventTimestamp" class="timeStamp">
   </div>
   <script type="text/javascript">
   // Convert UTC timestamp to local time and display in specified DOM element
   function convertAndDisplayUTCtime(date,hour,minutes,elementID) {
    var eventDate = new Date(''+date+' '+hour+':'+minutes+':00 UTC');
    eventDate.toString();
    $('#'+elementID).html(eventDate);
   }
   convertAndDisplayUTCtime('06/03/2015',16,32,'eventTimestamp');
   </script>

其他回答

将此用于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;
}

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

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

如果你不介意使用moment.js,并且你的时间是UTC时间,请使用以下格式:

moment.utc('6/29/2011 4:52:48 PM').toDate();

如果您的时间不是utc,而是您所知道的任何其他地区,则使用以下方法:

moment('6/29/2011 4:52:48 PM', 'MM-DD-YYYY', 'fr').toDate();

如果你的时间已经在本地,那么使用以下方法:

moment('6/29/2011 4:52:48 PM', 'MM-DD-YYYY');

在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

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

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

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