如何使用系统时区和UTC时间从服务器获取当前本地时间 [英] How to get the current local time using the system time zone and UTC time from the server in javascript

查看:274
本文介绍了如何使用系统时区和UTC时间从服务器获取当前本地时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在json响应中将UTC时间作为 Sat,19 May 2012 11:26:51 +0000 ,并将系统时区设置为 +0530 。如何使用两个可用结果将UTC时间转换为本地时间?我希望日期为 isoDate 格式和时间为 isoTime 格式。请帮助如何做到这一点?

I have got the UTC time as Sat, 19 May 2012 11:26:51 +0000 in the json response and have the system time zone as +0530. How can i convert the UTC time to the local time using the two available result? I want the date as isoDate format and time as isoTime format. Please help how to do that?

推荐答案

将JSON datetime转换为Date对象(使用没有+0000时区信息的字符串)并添加/减去客户端timezoneOffset:

Convert the JSON datetime to a Date Object (use the string without the +0000 timezone information) and add/subtract the client side timezoneOffset:

var received = new Date('Sat, 19 May 2012 11:26:51'),
    clientDate = new Date(new Date().getTimezoneOffset()*-60000 
                  + received.getTime());
//note: -60000 reverses the sign of the timezone offset 
//      clientDate is calculated in milliseconds.
//alternatively you can set [received] directly to the local datetime using:
received.setMinutes(received.getMinutes()+(-(new Date().getTimezoneOffset()));

在我的时区(GMT + 2) clientDate 阅读 Sat May 19 2012 13:26:51 GMT + 0200

In my timezone (GMT+2) clientDate now reads Sat May 19 2012 13:26:51 GMT+0200

这篇关于如何使用系统时区和UTC时间从服务器获取当前本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆