javascript时区转换器 [英] javascript timezone converter

查看:52
本文介绍了javascript时区转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种方法将未来的时间转换为不同的时区,而不依赖于用户的计算机时间。



在注册时,用户提供他的时区。当他登录时,我计算UTC时间和他的时间之间的分钟偏移量,并将该偏移量注入页面,以便javascript函数可以进行转换。这样的事情:

  var TheUTCTime = new Date(UserTime.getTime() -  TimeZoneOffsetInMinutes * 60000); 

和其他方式一样:

  var TheUserTime = new Date(UTCTime.getTime()+ TimeZoneOffsetInMinutes * 60000); 

只要偏移量没有改变,这对转换时间非常有效。例如,由于夏令时,在美国东部时间和UTC之间,根据一年中的月份,相差300分钟或360分钟。



我的功能运作良好转换今天的日期,但我想要的东西可以1)在一年中的任何一天做同样的事情,2)不依赖于用户的内部时钟或时区。



我怎么能这样做?



谢谢。

解决方案

< blockquote>

我的功能很好地转换今天的日期,但我想要的东西可以1)在一年中的任何一天做同样的事情2)不依赖于用户的内部时钟或时区。


如果你想将另一个UTC时间转换为用户的当地时间,你知道知道他们的时区。这几乎是时区的定义:UTC与本地时间之间的映射(或等效地,UTC与本地时间之间的偏移)。



正如您所见,获取当前偏移是不够的,因为夏令时转换(以及对时区的任何其他更改 - 它们的变化比您预期的要多)。



基本上没有办法解决这个问题:你将 向用户询问他们的时区。您可以根据UTC的当前偏移量进行良好的 guess ,并可能对其IP地址进行地理编码,但您必须与它们进行确认。 (例如,他们可能正在旅行或某事,而不是在他们的家时区。)


I need a way to convert times in the future to different timezones without relying on the user's computer time.

At registration time, the user supplies his timezone. When he logs in, I calculate the offset in minutes between the UTC time and his time and inject that offset into the page so that a javascript function can do the conversions. Something like this:

var TheUTCTime = new Date(UserTime.getTime() - TimeZoneOffsetInMinutes * 60000);

and like this for the other way around:

var TheUserTime = new Date(UTCTime.getTime() + TimeZoneOffsetInMinutes * 60000);

This works really well to convert times as long as the offset doesn't change. For instance, because of daylight saving, between US EST and UTC, there's a difference of 300 minutes or 360 minutes depending on the month in the year.

My functions work well to convert today's date but I'd like something that can 1) do the same thing for any day of the year and 2) doesn't depend on the user's internal clock or timezone.

How could I do this?

Thanks.

解决方案

My functions work well to convert today's date but I'd like something that can 1) do the same thing for any day of the year and 2) doesn't depend on the user's internal clock or timezone.

If you want to convert another UTC time into the user's local time, you have to know their time zone. That's pretty much the definition of a time zone: a mapping between UTC and local time (or equivalently, between UTC and the offset from local time).

As you've seen, getting the current offset isn't enough, because of daylight saving transitions (and any other changes to time zones - they vary more than you might expect).

Basically there's no way round this: you will have to ask the user for their time zone. You can make a good guess based on the current offset from UTC and possibly geocoding their IP address, but you'll have to confirm it with them. (For example, they may be on a trip or something, and not in their "home" time zone.)

这篇关于javascript时区转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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