How to get local time in another time zone

偶尔善良 提交于 2020-01-04 06:11:49

问题


Using pure javascript (no jquery nor plugins), how do I convert one local time to another timezone?

For situation:

I am doing a countdown timer and I've set the end date as a javascript variable. I want to convert that variable to a local time depending on the client location/time zone.

var maintenanceEndDate = new Date("11/10/2015 00:00"); //This is the initial time,  based on the administrator's location
var maintenanceEndDateOffset = ????  //The above time converted to local time

and THEN I would want to convert both to UTC.

Any ideas?


回答1:


var now = new Date();

This will give you the client date and time.

now.getTimezoneOffset()

Will give you the offset between that timezone and UTC.




回答2:


You could specify your maintenance end time in UTC and let the local browser handle the time conversion for you:

var maintenanceEndDate = new Date("2015-11-10T00:00:00Z");
document.write('Local time: ' + maintenanceEndDate.toString() + '<br>')
document.write('UTC time: ' + maintenanceEndDate.toISOString())



回答3:


I suggest you to dive into the momentjs library which does exactly what you need: http://momentjs.com/ and http://momentjs.com/timezone/



来源:https://stackoverflow.com/questions/33607894/how-to-get-local-time-in-another-time-zone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!