Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

datetime - Working with timezones and daylight savings time in Javascript

My single-page javascript app retrieves data in JSON format via REST calls. Dates come formatted using the UTC timezone in standard ISO8601 format, such as 2011-02-04T19:31:09Z.

When signing up for the service, users select their timezone from a drop down list. This timezone could be different than the user's browser's timezone. The javascript app knows what the user's selected timezone is at all times.

I know how to convert the UTC string into a date. I understand that Javascript only represents dates in the local timezone.

But I'm having troubles figuring out how to display a date formatted for a timezone OTHER than the user's local timezone. It must account for DST on all dates. Internally, I want to deal with all dates as UTC and only convert to string representation of a date in another timezone at display time. I need to display the dates in the timezone selected in the user's profile, not their browser's timezone.

I've experimented with the server sending the timezone offset difference in milliseconds between the user's browser's timezone and the user's profile timezone. But I've found I can't just send one offset value, but need to send an offset for every date to account for variations in DST.

Any suggestions or sample code on how to display dates formatted in various timezones? The options I've found so far:

  1. Server sends dates as strings already formatted in the right timezone and no date parsing or manipulation is done on the client. This makes doing certain things on the client difficult if not impossible.
  2. Use a library such as https://github.com/mde/timezone-js, which includes the entire Olson TZ database into Javascript. This means longer load times more memory usage, etc.
  3. Send a timezoneOffsetMillis value with every date sent to the client. This results in messy JSON data and non-optimal REST interfaces.

Are there any simpler or better solutions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

2 is a bad idea since, as you pointed out, it increases load times. If I were you I would do a combination of 1 and 3. I don't agree that this makes the JSON data messy or the REST interface non-optimal.

This is a classic tradeoff where to accept a bit more complexity in the protocol in order to simplify the client-side code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...