Andy Phillips
Andy Phillips

Reputation: 247

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 :-)

Upvotes: 0

Views: 4239

Answers (1)

Maggie Pint
Maggie Pint

Reputation: 2452

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:

moment.tz(dateTime, '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
moment.tz('2016-12-30', 'Europe/London').unix()
1483056000
//parse that timestamp back to my local time
moment.unix(1483056000).format()
"2016-12-29T18:00:00-06:00"

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:

moment.utc(dateTime)

Upvotes: 5

Related Questions