how to handle DST and timezones in JavaScript

柔情痞子 提交于 2020-01-05 03:41:08

问题


What is the best approach for dealing with DST values when your web service accepts requests from different timezones than that of your server?

My webservice accepts date strings using the ISO8601 standard (2012-02-21T05:00:00.000-05:00)

I want to account for DST but don't want the overhead of maintaining or connecting to a database to get the DST for each request which comes in from a different timezone to my server.

One approach im considering is using the servers default DST settings and then for each request that comes in convert it to the same timezone as my server is in. Then when the processing is done , convert the string back to the timezone of the client and return. The conversion of the response data could be done on the server or the client.

Any suggestions?


回答1:


Here's what I would do. Before you submit your data/time, parse the strings into a JavaScript Date object. Then call getTime() and submit that value. getTime() returns the number of milliseconds since the UTC epoch, so in effect, it normalizes your times. Then when you return data to the user, pass in your UTC millisecond value to the constructor of a Date object and display the time as you would. By default, it'll display in the user's timezone.




回答2:


You could also take a look at the XDate project for handling date objects in Javascript. It's quite similar to JodaTime (in Java). Very easy to use and semantic.

XDate project



来源:https://stackoverflow.com/questions/9380365/how-to-handle-dst-and-timezones-in-javascript

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