Boris Daka
Boris Daka

Reputation: 603

Convert JS Date + Time to Different Time Zones

Suppose a user of your website select days times and account timezone:

2015-09-02 14:15:00 
2015-09-02 15:30:00
2015-09-03 17:10:00

Timezone: "America/Los_Angeles"

You send and keep this information at the server and the server should execute A function at the exact same local time the user needs it. At later time the user can change his timezone to "Europe/Stockholm" and we re-adjust the dates by this timezone.

How should the flow from client to server should look like? What are my actions? There is a lot of wrong and misinformation over the internet I really need some solid advice.

Here is what I came up with:

I save this javascript object to the database moment.tz("2015-09-02 14:15:00", "America/Los_Angeles").toDate()

and based on this date I execute the function and if we need to recalculate the timezone we just take days/times and use the same thing.

I have read that this way might not be adjusted to day light saving time and it's wrong. Help?

Upvotes: 1

Views: 1616

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241420

I'll answer this by dissecting your question into the relevant parts.

... the server should execute A function at the exact same local time the user needs it.

Ok, so I'll assume you are scheduling events to run in the future. This is important, as the approach would be completely different if you were recording timestamps for events that have already occurred.

... at later time the user can change his timezone to "Europe/Stockholm" and we re-adjust the dates by this timezone.

You should not adjust the dates of the events. Associate the time zone with the event, not with the user. You can have a per-user time zone also, and you can adjust for that time zone on display - but you should leave the original event time and time zone alone unless the user directly edits it. (Note, I'm making several assumptions about your project internals here, but this is best general advice).

I save this javascript object to the database moment.tz("2015-09-02 14:15:00", "America/Los_Angeles").toDate()

The JS Date object represents an instant in time, but projects it using the local time zone of where the code is running. Therefore, any time zone adjustment you do with moment-timezone will be undone as soon as you call toDate. You should avoid calling toDate. Instead, use moment's functions, such as format, which can retain the time zone offset.

I have read that this way might not be adjusted to daylight saving time and it's wrong.

Not sure where you read that, but that's incorrect. Both the Date object and a moment object (whether using moment-timezone or not) can properly account for DST.

You may also wish to review some of the other answers I've written about scheduling future events. Start with this one, and follow links to other posts.

Upvotes: 1

Related Questions