从服务器我得到一个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

其他回答

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

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

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

把这个函数记在脑子里:

<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,""));

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

采用YYYY-MM-DD hh:mm:ss格式:

var date = new Date('2011-06-29T16:52:48+00:00');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"

要从YYYY-MM-DD hh:mm:ss格式转换,请确保您的日期遵循ISO 8601格式。

Year: 
    YYYY (eg 1997)    
Year and month: 
    YYYY-MM (eg 1997-07)
Complete date: 
    YYYY-MM-DD (eg 1997-07-16)
Complete date plus hours and minutes:
    YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)    
Complete date plus   hours, minutes and seconds:
    YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)    
Complete date plus hours, minutes, seconds and a decimal fraction of a second
    YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) where:

YYYY = four-digit year
MM   = two-digit month (01=January, etc.)
DD   = two-digit day of month (01 through 31)
hh   = two digits of hour (00 through 23) (am/pm NOT allowed)
mm   = two digits of minute (00 through 59)
ss   = two digits of second (00 through 59)
s    = one or more digits representing a decimal fraction of a second
TZD  = time zone designator (Z or +hh:mm or -hh:mm)

需要注意的重要事项

你必须用T分隔日期和时间,空格在某些浏览器中不起作用 您必须使用这种格式+hh:mm设置时区,使用字符串作为时区(例如:'UTC')将在许多浏览器中不起作用。+hh:mm表示与UTC时区的偏移量。

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

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

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