如何忽略用户的时区并强制Date()使用特定的时区 [英] How to ignore user's time zone and force Date() use specific time zone
问题描述
在JS应用程序中,我从服务器(Ajax)收到时间戳(eq。 1270544790922
)。
In an JS app, I receive timestamp (eq. 1270544790922
) from server (Ajax).
基于该时间戳记,我使用以下方式创建 Date
对象:
Basing on that timestamp I create Date
object using:
var _date = new Date();
_date.setTime(1270544790922);
现在, _date
当前用户的解码时间戳区域时区。我不想要这个。
Now, _date
decoded timestamp in current user locale time zone. I don't want that.
我想要_ date
将这个时间戳转换为当前时间赫尔辛基在欧洲(不考虑当前用户的时区)。
I would like _date
to convert this timestamp to current time in city of Helsinki in Europe (disregarding current time zone of the user).
我该怎么做?
推荐答案
JS在用户本地时间。也可以创建该时间戳的GMT版本。第一步是确认所呈现的时间实际上是用户的时间,而不是GMT。尝试使用。
A date object in JS is in the user's local time. It is also possible to create a GMT version of that timestamp. The first step is to confirm that the time being presented is in fact the users time and not GMT. Try using.
_date.getTimezoneOffset();
一旦确定。您可以添加该时区偏移以及+2的Helsenki偏移量。我假设实际上是你所提到的用户本地时间。尝试:
Once that is determined. You can add that time zone offset along with the offset for Helsenki which is +2. I am assuming that is actually the users local time as you mentioned. Try:
var _helsenkiOffset = 2*60*60000;//maybe 3 [h*60*60000 = ms]
var _userOffset = _date.getTimezoneOffset()*60000; // [min*60000 = ms]
var _helsenkiTime = new Date(_date.getTime()+_helsenkiOffset+_userOffset);
这可能会更接近...所以基本上我们只是推动两个小时, gmt偏移。唯一的问题是DST;然而,如果服务器给你一个时间戳,它可能已经是DST。否则,请尝试以下方式: http://www.csgnetwork.com/timezoneproginfo.html 和在if语句中加或减1小时。
That might be a little closer... So essentially we are just pushing 2 hours forward and accounting for gmt offset. The only thing in question is DST; however, if the server is giving you a time stamp it might already be DST. Otherwise, try something like this: http://www.csgnetwork.com/timezoneproginfo.html and in an if statement add or subtract 1 hour.
这篇关于如何忽略用户的时区并强制Date()使用特定的时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!