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.
Use the toLocaleString() method to initialize a date with time zone, e.g. date. toLocaleString('en-US', { timeZone: 'America/Los_Angeles'}) . The method can be passed the locale and the time zone as parameters and returns a string that represents the date according to the provided values.
The date_default_timezone_set() function sets the default timezone used by all date/time functions in the script.
Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST.
JavaScript's internal representation uses the “universal” UTC time but by the time the date/time is displayed, it has probably been localized per the timezone settings on the user's computer. And, indeed, that's the way JavaScript is set up to work.
using .setUTCHours()
it would be possible to actually set dates in UTC-time, which would allow you to use UTC-times throughout the system.
You cannot set it using UTC in the constructor though, unless you specify a date-string.
Using new Date(Date.UTC(year, month, day, hour, minute, second))
you can create a Date-object from a specific UTC time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With