I have a script that reads the users timezone and displays a time according to users. How do I display the timezone abbreviation?
I have a gaming site, and on posts we write "We'll be playing live at 7:00". Users from around the world read our blog, and want to watch live. I have the following script that is supposed to read the users timezone, and displays the time according to where the user lives.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Localtime</title>
</head>
<body>
We'll be playing live at <span class="localtime">7:00PM EDT</span>
<script src="//cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js"></script>
<script
var els = document.getElementsByClassName('localtime');
for (var i = 0, l = els.length; i < l; i++)
els[i].innerHTML =
Date.parse(els[i].innerHTML).toLocaleString();
</script>
</body>
</html>
How do I display a user-specific timezone abbreviation beside the time, so users know that the time is based on their timezone?
A few things:
Date().toString()
, but it is highly dependent on the browser. It may come out as an abbreviation, or as a localized full name or id of the time zone, or not at all.The best approach would be to start with an exact moment (either as UTC or with an offset), then render that to the correct format. For example, (with moment.js)
var m = moment("2013-08-06T19:00:00-04:00"); // this is 7PM EDT
var s = m.format("HH:mm ([UTC]ZZ)"); // example: "16:00 (UTC-0700)"
Updated version of the DateJS core code (and will be fixing open bugs in the future) available here:
https://github.com/abritinthebay/datejs/
However it sounds like you're just looking for DateJS's format or toString methods.
For example:
var tmp = Date.parse("2013-09-05T22:40:00Z");
var time = tmp.format("g:i A T");
this would leave time with the string "3:40 PM PDT"
This doesn't rely on internal browser issues as DateJS performs a lookup based on the offset for the date (which doesn't change per browser).
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