简体   繁体   中英

Convert a time to a different timezone using javascript

I have a time which is in the PHP format: g:ia T eg 2:00pm AEST. I then have printed in a hidden div below this the timezone in the common format: Australia/Sydney . This timezone is the timezone used to output that time (I have several of these times and different corresponding timezones on my page). I have a link at the top of my page which allows the user to convert all the times into their local time (which isn't working yet). When the user clicks this link it outputs their timezone in the same format eg Europe/London.

So how do I change the times to the users timezone when I have the time and the timezone used to create that time, and the users timezone using javascript?

While I am still looking into a specific code answer for myself I can confirm from my research that Moment Timezone is the easiest way to convert times to different timezones using javascript. Thanks James Thorpe for pushing me in the right direction. moment-timezone.js has been built specifically for this purpose but regular moment.js won't convert between timezones (at least not easily). Here is moment-timezone.js in action:

var jun = moment("2014-06-01T12:00:00Z");
var dec = moment("2014-12-01T12:00:00Z");

jun.tz('America/Los_Angeles').format('ha z');  // 5am PDT
dec.tz('America/Los_Angeles').format('ha z');  // 4am PST

jun.tz('America/New_York').format('ha z');     // 8am EDT
dec.tz('America/New_York').format('ha z');     // 7am EST

jun.tz('Asia/Tokyo').format('ha z');           // 9pm JST
dec.tz('Asia/Tokyo').format('ha z');           // 9pm JST

jun.tz('Australia/Sydney').format('ha z');     // 10pm EST
dec.tz('Australia/Sydney').format('ha z');     // 11pm EST

You can find out more information here: http://momentjs.com/timezone/ and also there's a good wiki here about timezones more generally: https://stackoverflow.com/tags/timezone/info

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM