How do you create a JavaScript Date object with a set timezone without using a string representation
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)
Give the correct date but it thinks that date is GMT+01:00 due to daylight savings time.
The problem here is that I then give 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.
The accepted answer pointed me in the right direction, however just using
setUTCHours
by itself changed:Apr 5th 00:00 GMT+01:00
to
Apr 4th 23:00 GMT+01:00
I then also had to set the UTC date, month and year to end up with
Apr 5th 01:00 GMT+01:00
which is what I wanted
Answer:
using
.setUTCHours()
it would be possible to actually set dates in UTC-time, which would allow you to use UTC-times throughout the system.
Using
new Date(Date.UTC(year, month, day, hour, minute, second))
you can create a Date-object from a specific UTC time.
COMMENTS