問題描述
我有一個網(wǎng)頁,其中包含日、月和年的三個下拉菜單.如果我使用接受數(shù)字的 JavaScript Date
構(gòu)造函數(shù),那么我將獲得當(dāng)前時區(qū)的 Date
對象:
I have a web page with three dropdowns for day, month and year. If I use the JavaScript Date
constructor that takes numbers, then I get a Date
object for my current timezone:
new Date(xiYear, xiMonth, xiDate)
給出正確的日期,但由于夏令時,它認為日期是 GMT+01:00.
Give the correct date, but it thinks that date is GMT+01:00 due to daylight savings time.
這里的問題是,然后我將此 Date
傳遞給 Ajax 方法,當(dāng)日期在服務(wù)器上被反序列化時,它已被轉(zhuǎn)換為 GMT,因此丟失了一個小時,從而將日期向后移動一.現(xiàn)在我可以將日、月和年單獨傳遞到 Ajax 方法中,但似乎應(yīng)該有更好的方法.
The problem here is that I then pass this Date
to an Ajax method and when the date is deserialised on the server it has been converted to GMT and so lost an hour which moves the day back by one.
Now I could just pass the day, month, and year individually into the Ajax method, but it seems that there ought to be a better way.
接受的答案為我指明了正確的方向,但是僅使用 setUTCHours()
本身就發(fā)生了變化:
The accepted answer pointed me in the right direction, however just using setUTCHours()
by itself changed:
Apr 5th 00:00 GMT+01:00
到
Apr 4th 23:00 GMT+01:00
然后我還必須設(shè)置 UTC 日期、月份和年份以結(jié)束
I then also had to set the UTC date, month and year to end up with
Apr 5th 01:00 GMT+01:00
這正是我想要的.
推薦答案
使用 .setUTCHours()
可以在 UTC-time 中實際設(shè)置日期,這將允許您使用 UTC-整個系統(tǒng)的時間.
using .setUTCHours()
it would be possible to actually set dates in UTC-time, which would allow you to use UTC-times throughout the system.
你不能在構(gòu)造函數(shù)中使用 UTC 設(shè)置它,除非你指定一個日期字符串.
使用 new Date(Date.UTC(year, month, day, hour, minute, second))
您可以從特定的 UTC 時間創(chuàng)建 Date-object.
Using new Date(Date.UTC(year, month, day, hour, minute, second))
you can create a Date-object from a specific UTC time.
這篇關(guān)于創(chuàng)建具有設(shè)定時區(qū)的日期而不使用字符串表示的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!