如何将日期转换为GMT? [英] How can I convert a date to GMT?
问题描述
如何将不同时区的日期转换为GMT 0?假设我有这样的日期
How to convert date of different timezones to GMT 0? Let say I have dates like this
Fri Jan 20 2012 11:51:36 GMT-0500
Fri Jan 20 2012 11:51:36 GMT-0300
Fri Jan 20 2012 11:51:36 GMT+0500
to
Fri Jan 20 2012 06:51:36 GMT
Fri Jan 20 2012 08:51:36 GMT
Fri Jan 20 2012 16:51:36 GMT
这些是我的日期我在不同的时区通过新的Date()。toString()
。是否有任何js方法来检测时区并进行相应的转换?
these are dates I am getting via new Date().toString()
on different timezones. Is there any js method to detect timezone and convert accordingly?
编辑:后三个日期不是前三个日期的GMT转换时间。例如, 2012年1月20日星期五11:51:36 GMT-0500
格林尼治标准时间 2012年1月20日星期五16:51:36 GMT
不 2012年1月20日星期五06:51:36 GMT
。 GMT-0500落后于GMT,而不是未来,因此您必须添加偏移以获得GMT,而不是减去它。
The second three dates are not the GMT converted times of the first three. For example, Fri Jan 20 2012 11:51:36 GMT-0500
in GMT is Fri Jan 20 2012 16:51:36 GMT
not Fri Jan 20 2012 06:51:36 GMT
. GMT-0500 is behind GMT, not ahead, so you have to add the offset to get GMT, not subtract it.
推荐答案
您可以使用 Date.getTimezoneOffset()
。这将返回您的日期和GMT之间的时差,以分钟为单位。
You can use Date.getTimezoneOffset()
. This returns the time difference between your date and GMT in minutes.
将此乘以60,000(一分钟内的毫秒数)以获得毫秒数并从日期中减去以创建新日期。
Multiply this by 60,000 (milliseconds in a minute) to get the milliseconds and subtract from the date to create a new date.
new Date(date.valueOf()+ date.getTimezoneOffset()* 60000);
这篇关于如何将日期转换为GMT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!