Andy Phillips Andy Phillips - 1 year ago 162
Javascript Question

Moment.js Timezone - CONSIDER a date/time to be in a different timezone when outputting

I know this seems like a straight forward question - but although Moment.js and moment timezone are very powerful tools for getting/setting and formatting dates..

I'm having an issue snapping my application to a single timezone.

What I want, is for a user to choose from a date/time picker - and to send that as a unix timestamp in UTC.. but the date/time picker MUST be considered to be BST.

In other words, even if you're using the site from abroad - the date/time you select should be the UTC value for if you had chosen it in the UK.

var local = moment(dateTime).unix();
var london = moment(dateTime).tz('Europe/London').unix();
var berlin = moment(dateTime).tz('Europe/Berlin').unix();

All 3 variables will equal the SAME UTC timestamp on the same machine, but a different timestamp on another machine running in a different timezone.

Think about it... if my date/time was 3pm on Saturday.. that's a DIFFERENT UTC in London than it is in Berlin, since it will occur one hour earlier in Berlin.

How do I force a date/time to be considered as a specific timezone?

Thanks :-)

Answer Source

Assuming dateTime is an ISO8601 string, and you want the date to be in the Europe/London timezone at all times all you need is:, 'Europe/London').unix()

This tells moment to interpret that time as London time, provided that it does not have a specified offset. If it has an offset, it is going to convert from the time of the offset to London time.

So, for me in America/Chicago, you can see the effect of this:

//unix timestap in london time'2016-12-30', 'Europe/London').unix()
//parse that timestamp back to my local time

Keep in mind that London has multiple offsets due to Daylight Saving Time. I think this is what you want.

If you wanted it to always keep a fixed offset of +0, then you could just use UTC: