在Javascript中使用浏览器区域以外的时区

时间:2010-06-23 23:22:52

标签: javascript ajax timezone

我有一个页面,允许用户查看和编辑存储在数据库中的时间(带日期)。时间以UTC格式存储在数据库中,并附加到具有不同时区的位置。当用户查看它们在附加时区中显示的时间时,不一定是浏览器的时区。然后,用户应该能够编辑时间并制作和AJAX请求。我需要能够在javascript中将输入的时间从任意时区转换为UTC,但唯一允许的转换javascript是从浏览器时区到UTC。在javascript中传递绝对偏移量是行不通的,因为用户应该能够在夏令时之前或之后编辑时间。这似乎应该是一个已经解决过的问题...任何指针?

3 个答案:

答案 0 :(得分:3)

这是一个非常讨厌的问题。只要用户在他/她自己的时区(或GMT)中出现所有时间,您就没有问题。但是要求JS为不同的语言环境提供准确的本地夏令时值是令人讨厌的事情。浏览器知道GMT和当地时间(并且由于操作系统),它也知道DST何时在本地启动。但是,如果不更改用户的系​​统时区信息,JS无法告知DST何时在另一个区域设置中启动。 DST生效的规则不仅因国家而异,日期可能会随着时间的推移而意外变化(还记得北美国家最近移动DST日期吗?)。您可以很容易地在服务器上找出区域设置DST详细信息并将其传达给浏览器。但是完全在浏览器中尝试它可能是不切实际的。您可以在应用程序中使用某种DST_changeover_by_locale数组,但是您需要定期更新它。

[编辑]关于JS Date对象如何在时区方面起作用似乎存在一些混淆。以下是一些有用的观点:

时区偏移

// Create a time in winter (Standard time)
dt = new Date('Jan 1 2010 12:00:00 GMT-0000'); 
alert(dt.getTimezoneOffset()); 
// In Japan right now, users would see "-540"
// In New York right now, users would see "300"

// Create a time in summer (DST)
dt = new Date('Jul 1 2010 12:00:00 GMT-0000'); 
alert(dt.getTimezoneOffset()); 
// In Japan right now, users would see "-540"
// In New York right now, users would see "240"
// NOTE: Japan has no DST while NY does

解析当地时间

// The following will all return the same time string, which will be 
// the time according to the user's OS time settings and locale
alert((new Date('Jun 25 2010 13:30:00 GMT-0230'))); // Newfoundland time
alert((new Date('Jun 25 2010 13:00:00 GMT-0300'))); // Atlantic time
alert((new Date('Jun 25 2010 12:00:00 GMT-0400'))); // Eastern time
alert((new Date('Jun 25 2010 11:00:00 GMT-0500'))); // Central time
alert((new Date('Jun 25 2010 10:00:00 GMT-0600'))); // Mountain time
alert((new Date('Jun 25 2010 9:00:00 GMT-0700'))); // Pacific time

时间戳

// If you don't want to work with strings, use numbers instead. 
// These return the JS timestamp for the same values above. 
// The value is a *delta*, so it is unaffected by DST.
alert((new Date('Jun 25 2010 13:30:00 GMT-0230')).getTime()); // Newfoundland time
alert((new Date('Jun 25 2010 13:00:00 GMT-0300')).getTime()); // Atlantic time
alert((new Date('Jun 25 2010 12:00:00 GMT-0400')).getTime()); // Eastern time
alert((new Date('Jun 25 2010 11:00:00 GMT-0500')).getTime()); // Central time
alert((new Date('Jun 25 2010 10:00:00 GMT-0600')).getTime()); // Mountain time
alert((new Date('Jun 25 2010 9:00:00 GMT-0700')).getTime()); // Pacific time

答案 1 :(得分:0)

我认为您不必在浏览器上进行时区转换。您可以在客户端上显示“不透明”的日期时间,让他们对其进行修改,然后根据需要发布到服务器以将其转换为UTC。

答案 2 :(得分:0)

我不确定是否应将此作为答案,但我不能发表评论,因为我没有将该临时帐户与此ID相关联...

不幸的是,看起来像做时区计算服务器端是唯一干净的方法,但我仍然希望有人可能有另一个解决方案。按照惯例,在本代码中,所有时间都应该以UTC格式发送,并且我希望尽可能避免破坏该约定(如果可能的话,在其他地方使我们可能使用服务调用会让人感到困惑)。