如何在JavaScript中处理DST和时区 [英] how to handle DST and timezones in JavaScript

查看:55
本文介绍了如何在JavaScript中处理DST和时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您的Web服务接受与服务器时区不同的时区的请求时,处理DST值的最佳方法是什么?

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

我的网络服务使用ISO8601标准(2012-02-21T05:00:00.000-05:00)接受日期字符串

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

我想考虑DST,但不希望维护或连接到数据库以获取来自不同时区到我服务器的每个请求的DST的开销.

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.

我正在考虑的一种方法是使用服务器的默认DST设置,然后针对传入的每个请求将其转换为与服务器所在的时区相同.然后,​​在处理完成后,将字符串转换回当前的时区.客户和回报.响应数据的转换可以在服务器或客户端上完成.

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.

有什么建议吗?

推荐答案

这就是我要做的.在提交数据/时间之前,请将字符串解析为JavaScript Date对象.然后调用getTime()并提交该值. getTime()返回自UTC时代以来的毫秒数,因此实际上,它使您的时间归一化.然后,当您将数据返回给用户时,将您的UTC毫秒值传递给Date对象的构造函数,并按照您的意愿显示时间.默认情况下,它将显示在用户的时区中.

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.

这篇关于如何在JavaScript中处理DST和时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆