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

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


当前回答

在尝试了这里发布的其他一些没有好的结果之后,这似乎对我有用:

convertUTCDateToLocalDate: function (date) {
    return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(),  date.getHours(), date.getMinutes(), date.getSeconds()));
}

这是相反的,从本地日期到UTC:

convertLocalDatetoUTCDate: function(date){
    return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}

其他回答

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

根据@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':

theDate = new Date( Date.parse('6/29/2011 4:52:48 PM UTC'));

之后,使用toLocale()*函数族以正确的地区显示日期

theDate.toLocaleString();  // "6/29/2011, 9:52:48 AM"
theDate.toLocaleTimeString();  // "9:52:48 AM"
theDate.toLocaleDateString();  // "6/29/2011"

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)

把这个函数记在脑子里:

<script type="text/javascript">
function localize(t)
{
  var d=new Date(t+" UTC");
  document.write(d.toString());
}
</script>

然后为页面主体中的每个日期生成以下内容:

<script type="text/javascript">localize("6/29/2011 4:52:48 PM");</script>

删除GMT和时区,修改以下行:

document.write(d.toString().replace(/GMT.*/g,""));