简体   繁体   中英

How to create dates in another timezone, in browser Javascript

I have a client side web application where the user must create Dates for timezones other then their own, and I'm not sure of the best way to do this.

Using Moment Timezone, I know how I can change a time into another timezone. That is, convert Nov 18 2013 11:00:00 GMT-0500 to Nov 19 2013 03:00:00 GMT+1100 . These still represent the same absolute time, but just with a different 'view'.

What I need to do is convert, respecting daylight savings, Nov 18 2013 11:00:00 America/Toronto" to Nov 18 2013 11:00:00 Australia/Sydney (which are different absolute times).

So far the only way I can come up with is to create a Date , serialize it to string, and then parse it with Moment Timezone, something like:

localEvent = new Date(2015, 03, 10, 18, 30)
eventStr = localEvent.toString().split('GMT')[0]
# eventStr = 'Fri Apr 10 2015 18:30:00'
event = moment.tz(eventStr, 'Australia/Sydney')

So now this code will create the exact same point in time regardless of which timezone the browser is operating in.

But this feels very hacky, is there a better way to do this?

Yes, you can do that better:

var zone = moment().tz('Australia/Sydney');

var c = moment(new Date(2015, 03, 10, 18, 30));
c.utcOffset(zone.utcOffset(), true);
                             // ^--- this flag keeps the same time
                             //      while shifts a timezone

console.log(c.format());

JSFiddle: http://jsfiddle.net/8m6rdzqj/

How I found it: I just went through the moment and moment-timezone source: https://github.com/moment/moment-timezone/blob/master/moment-timezone.js#L347

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