从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
从服务器我得到一个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>
其他回答
在尝试了这里发布的其他一些没有好的结果之后,这似乎对我有用:
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());
}
@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); }
在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
UTC到本地到ISO -使用Molp Burnbright回答
因为服务器只接受ISO日期-时间,所以我将UTC转换为我的本地时区,并以ISO格式发送给服务器
在某处声明
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime() - date.getTimezoneOffset()*60*1000);
return newDate;
}
并在需要ISO格式的本地日期时间时执行此操作。
对我来说,上述解决方案并不奏效。
在IE中,UTC日期-时间到本地的转换有点棘手。 对我来说,来自web API的日期-时间是“2018-02-15T05:37:26.007”,我想按照当地时区进行转换,所以我使用了下面的JavaScript代码。
var createdDateTime = new Date('2018-02-15T05:37:26.007' + 'Z');