I want the server to always serve dates in UTC in the HTML, and have JavaScript on the client site convert it to the user's local timezone.
Bonus if I can output in the user's locale date format.
I want the server to always serve dates in UTC in the HTML, and have JavaScript on the client site convert it to the user's local timezone.
Bonus if I can output in the user's locale date format.
Seems the most foolproof way to start with a UTC date is to create a new
Date
object and use thesetUTC…
methods to set it to the date/time you want.Then the various
toLocale…String
methods will provide localized output.Example:
Some references:
Here's what I've used in past projects:
You could use the following, which reports the timezone offset from GMT in minutes:
Note : - this function return a negative number.
Don't know how to do locale, but javascript is a client side technology.
will have the client's time and date in it (as reported by their browser, and by extension the computer they are sitting at). It should be trivial to include the server's time in the response and do some simple math to guess-timate offset.
The
.getTimezoneOffset()
method reports the time-zone offset in minutes, counting "westwards" from the GMT/UTC timezone, resulting in an offset value that is negative to what one is commonly accustomed to. (Example, New York time would be reported to be +240 minutes or +4 hours)To the get a normal time-zone offset in hours, you need to use:
Important detail:
Note that daylight savings time is factored into the result - so what this method gives you is really the time offset - not the actual geographic time-zone offset.
In JS there are no simple and cross platform ways to format local date time, outside of converting each property as mentioned above.
Here is a quick hack I use to get the local YYYY-MM-DD. Note that this is a hack, as the final date will not have the correct timezone anymore (so you have to ignore timezone). If I need anything else more, I use moment.js.
The d.getTimezoneOffset() returns the time zone offset in minutes, and the d.getTime() is in ms, hence the x 60,000.