JS日期+时间转不同时区

Convert JS Date + Time to Different Time Zones

假设您网站的用户 select 天时间和帐户时区:

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

时区:“America/Los_Angeles"

您将此信息发送并保存在服务器上,服务器应在用户需要的同一本地时间执行功能。稍后用户可以将他的时区更改为 "Europe/Stockholm",我们将根据该时区重新调整日期。

从客户端到服务器的流程应该是什么样的?我的行为是什么?互联网上有很多错误和错误的信息,我真的需要一些可靠的建议。

这是我想出的:

我将这个javascript对象保存到数据库 moment.tz("2015-09-02 14:15:00", "America/Los_Angeles").toDate()

并根据这个日期执行函数,如果我们需要重新计算时区,我们只需要 days/times 并使用相同的东西。

我了解到这种方式可能无法调整为夏令时,这是错误的。帮忙?

我会把你的问题分解成相关部分来回答这个问题。

... 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.

您不应该调整活动的日期。将时区与事件相关联,而不是与用户相关联。你也可以有一个每个用户的时区,你可以调整显示的时区 - 但你应该保留原始事件时间和时区,除非用户直接编辑它。 (请注意,我在这里对您的项目内部做了一些假设,但这是最好的一般性建议)。

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

JS Date 对象表示一个瞬间,但使用代码 运行ning 所在的本地时区投影它。因此,您使用 moment-timezone 进行的任何时区调整都将在您调用 toDate 后立即撤消。你应该避免调用 toDate。而是使用moment的函数,比如format,可以保留时区偏移

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

不确定你在哪里读到的,但那是不正确的。 Date 对象和 moment 对象(无论是否使用时刻时区)都可以正确说明 DST。

您可能还希望查看我写的关于安排未来活动的一些其他答案。从 this one 开始,然后点击其他帖子的链接。