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 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.
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.
One line solution
Instead of 1422524805305, use the timestamp in milliseconds Instead of 330, use your timezone offset in minutes wrt. GMT (eg India +5:30 is 5*60+30 = 330 minutes)
This code will return your Date object formatted with the browser timezone.
Best Solution I have seen from this came from
http://www.codingforums.com/archive/index.php/t-19663.html
Print Time Function
Full Code Example
I used the timezone-js package.
: :
If you want to deal with the slightly different, but related, problem of creating a Javascript Date object from year, month, day, ..., including timezone – that is, if you want to parse a string into a Date – then you apparently have to do an infuriatingly complicated dance:
That is, you create a 'UTC time' using the date without timezone (so you know what locale it's in, namely the UTC 'locale', and it's not defaulted to the local one), and then manually apply the indicated timezone offset.
Wouldn't it have been nice if someone had actually thought about the Javascript date object for more than, oooh, five minutes....
getTimeZoneOffset is minus for UTC + z.