Javascript date object in different locale and timezone

…衆ロ難τιáo~ 提交于 2019-11-30 14:38:38

A couple of things to keep in mind.

Store all event datetimes in UTC time

Yes, there is no getting around this.

Find out all the timezones...

...of all the users in the system. You can use the following detection script: http://site.pageloom.com/automatic-timezone-detection-with-javascript. It will hand you a timezone key such as for example "America/Phoenix".

In your case you need to store the timezone together with the event, since a user may switch timezone - but the event will always have happened in a specific one. (argh)

Choose your display mechanism

If you want to localize your event dates with Javascript, there is a nifty library for that too (which can use the keys supplied with the previous script). Here: https://github.com/mde/timezone-js.

with that library you can for example do this:

var dt = new timezoneJS.Date(UTC_TIMESTAMP, 'America/New_York');

or

var dt = new timezoneJS.Date(2006, 9, 29, 1, 59, 'America/Los_Angeles');

where UTC_TIMESTAMP for example could be 1193855400000. And America/New_Yorkis the timezone you have detected when the event took place.

The dt object that you get from this will behave as a normal JavaScript Date object. But will automatically "correct" itself to the timezone you have specified (including DST).

If you want to, you can do all the corrections in the backend - before you serve the page. Since I don't know what programming language you are using there, I cannot give you any immediate tips. But basically it follows the same logic, if you know the timezone, and the UTC datetime -> you can localize the datetime. All programming languages have libraries for that.

You're missing the point of a Date object. It represents a particular point in time. As I speak, it is 1308150623182 all over the world. Timezone only comes into play when you want to display the time to the user. An operation like "adding a day" does not involve the time zone at all.

One possibility might be to use UTC date and time for everything. That way, there is nothing to convert.

Another is to have your server provide the time and date. Then you don't have to depend on the user to have it set correctly, and you don't have to worry about where your user's timezone is.

Meeple

Use getUTCDate(), getUTCHours(), ... instead of getDate(), getHours(),... getTimetoneOffset() could be useful, too.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!