Reputation: 14511
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?
Upvotes: 1
Views: 120
Reputation: 254886
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
Upvotes: 1