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.
For new projects, just use moment.js
This question is pretty old, so moment.js didn't exist at that time, but for new projects, it simplifies tasks like this a lot.
It's best to parse your date string from UTC as follows (create an ISO-8601 compatible string on the server to get consistent results across all browsers):
Now just use
m
in your application, moment.js defaults to the local timezone for display operations. There are many ways to format the date and time values or extract portions of it.You can even format a moment object in the users locale like this:
To transform a moment.js object into a different timezone (i.e. neither the local one nor UTC), you'll need the moment.js timezone extension. That page has also some examples, it's pretty simple to use.
With date from PHP code I used something like this..
We can call it like this
The best solution I've come across is to create [time display="llll" datetime="UTC TIME" /] Tags, and use javascript (jquery) to parse and display it relative to the user's time.
http://momentjs.com/ Moment.js
will display the time nicely.
To convert date to local date use toLocaleDateString() method.
To convert time to local time use toLocaleTimeString() method.
You can use
new Date().getTimezoneOffset()/60
for the timezone. There is also atoLocaleString()
method for displaying a date using the user's locale.Here's the whole list: Working with Dates
I mix the answers so far and add to it, because I had to read all of them and investigate additionally for a while to display a date time string from db in a user's local timezone format.
The datetime string comes from a python/django db in the format: 2016-12-05T15:12:24.215Z
Reliable detection of the browser language in JavaScript doesn't seem to work in all browsers (see JavaScript for detecting browser language preference), so I get the browser language from the server.
Python/Django: send request browser language as context parameter:
HTML: write it in a hidden input:
JavaScript: get value of hidden input e.g. en-GB,en-US;q=0.8,en;q=0.6/ and then take the first language in the list only via replace and regular expression
JavaScript: convert to datetime and format it:
See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
The result is (browser language is en-gb): 05/12/2016, 14:58