从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
当前回答
你可以使用moment.js文件来完成。
很简单,你只是提到了时区的位置。
示例:如果你要将你的datetime转换为亚洲/加尔各答时区,你必须只提到从moment.js中获得的时区地点的名称
var UTCDateTime="从UTC获得的日期"; var ISTleadTime =(时刻。tz (UTCDateTime,“非洲/阿比让”)).tz(“亚洲/加尔各答”)。格式(YYYY-MM-DD LT);
其他回答
把这个函数记在脑子里:
<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,""));
在javascript中将字符串转换为日期之前,将'UTC'附加到字符串中:
var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
将此用于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;
}
UTC到本地到ISO -使用Molp Burnbright回答
因为服务器只接受ISO日期-时间,所以我将UTC转换为我的本地时区,并以ISO格式发送给服务器
在某处声明
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime() - date.getTimezoneOffset()*60*1000);
return newDate;
}
并在需要ISO格式的本地日期时间时执行此操作。
我在safari/chrome/firefox浏览器中使用这种方法效果很好:
const localDate = new Date(`${utcDate.replace(/-/g, '/')} UTC`);