从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
当前回答
tl;dr (new Date('6/29/2011 4:52:48 PM UTC')).toString()
源字符串必须指定时区或UTC。
一行程序:
(new Date('6/29/2011 4:52:48 PM UTC')).toString()
结果在我的一个web浏览器:
"Wed Jun 29 2011 09:52:48 GMT-0700 (Pacific Daylight Time)"
这种方法甚至适当地选择标准/日光时间。
(new Date('1/29/2011 4:52:48 PM UTC')).toString()
结果在我的浏览器:
"Sat Jan 29 2011 08:52:48 GMT-0800 (Pacific Standard Time)"
其他回答
在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
根据@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>
使用dayjs库:
(new Date()).toISOString(); // returns 2021-03-26T09:58:57.156Z (GMT time)
dayjs().format('YYYY-MM-DD HH:mm:ss,SSS'); // returns 2021-03-26 10:58:57,156 (local time)
(在nodejs中,你必须在使用它之前:const dayjs = require('dayjs'); 在其他环境下,请阅读dayjs文档。)
如果有人想要显示转换后的时间到特定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();
}
我知道这个答案已经被接受了,但我来到这里是因为谷歌,我确实从接受的答案中得到了灵感,所以如果有人需要,我确实想分享它。
你应该得到(UTC)偏移量(分钟)的客户端:
var offset = new Date().getTimezoneOffset();
然后对从服务器得到的时间做相应的加减运算。
希望这能有所帮助。