javascript 如何避免 JQuery datepicker 的时区问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22717201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to avoid time zone issues with JQuery datepicker
提问by jumps4fun
I'm using datepicker in an input form, and sending the results through json to a database. I am using this line, to get the date from the datePicker:
我在输入表单中使用 datepicker,并通过 json 将结果发送到数据库。我正在使用这一行,从 datePicker 获取日期:
date = $("#datepicker").datepicker('getDate');
Now, I would expect this to return 2014-04-03T00:00:00.000Z
现在,我希望这会回来 2014-04-03T00:00:00.000Z
But in fact it returns 2014-04-02T22:00:00.000Z
但实际上它返回 2014-04-02T22:00:00.000Z
Notice the two hour difference, which unintentionally changes the day of month as well. I have no use for the hours and the smaller time units. However I do want the date to be right, without adding a dreaded +1
to my code. I suspect this has something to do with time zones, but I can't seem to find a solution to it in the documentation, or other Q&A's online. Could anyone point me in the right direction? My time zone is GMT +1 if that matters.
请注意两小时的差异,这也会无意中改变月份中的某一天。我没有使用小时和较小的时间单位。但是我确实希望日期是正确的,而不是+1
在我的代码中添加一个可怕的东西。我怀疑这与时区有关,但我似乎无法在文档或其他在线问答中找到解决方案。有人能指出我正确的方向吗?如果重要的话,我的时区是 GMT +1。
Thanks :)
谢谢 :)
回答by jumps4fun
I solved this a while ago, but forgot to post an answer.
After retrieving date
, this is how i fixed it:
我不久前解决了这个问题,但忘了发布答案。检索后date
,这是我修复它的方式:
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
voilla
瞧
回答by user2542080
I could not figure out what you did there so I came up with a bit of a hackterrific solution.
我无法弄清楚你在那里做了什么,所以我想出了一个非常棒的解决方案。
I took the value of the alt field in UNIX:
我取了 UNIX 中 alt 字段的值:
$( function() {
$( "#datepicker" ).datepicker({
altField: "#alternate",
altFormat: "@",
});
It came out all sorts of weird with 3 extra 0's and a day behind my time zone. So I figured out the difference and added it on.
结果很奇怪,有 3 个额外的 0,比我的时区晚了一天。所以我找出了差异并添加了它。
var a = document.getElementById("alternate").value; // take alternative field UnixTimeStamp value
a = a.slice(0, -3); // get rid of 3 extra 0's
a = +a + +57000; // convert to Thai time