I have a web application that displays datetime stamps on every page, for example:
December 12, 2009 6:00 pm
I would like to dynamically detect the user's timezone and alter the display using JavaScript.
So the New York user would see:
December 12, 2009 6:00 pm
While the California user would see:
December 12, 2009 3:00 pm
Any suggestions?
You can use Date.getTimeZoneOffset() to get the local offset from GMT.
var date = new Date();
var offset = date.getTimezoneOffset();
From there its a SMOP. Using the Javascript Date object you can call date.toDateString
to get a human readable date. If you need it server side, have the Javascript send the offset to your server with a GET or POST.
Formatting the date is another story. Javascript doesn't provide much built in. You could hack it up yourself, but that way bugs and madness lies. Date formatting is something any good Javascript library should provide. For example, JQuery has Datepicker.formatDate.
Here is how you could do it with the wonderful "progressive enhancement":
Output the date where you want it to appear, but be sure to specify its timezone (I use GMT here, but you could use UTC, etc). Then swap it out with the local time on load (Automatically handled by JavaScript if the original timezone is provided).
<div id="timestamp">December 12, 2009 6:00 pm GMT</div>
<script type="text/javascript">
var timestamp = document.getElementById('timestamp'),
t = new Date(timestamp.innerHTML),
hours = t.getHours(),
min = t.getMinutes() + '',
pm = false,
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
if(hours > 11){
hours = hours - 12;
pm = true;
}
if(hours == 0) hours = 12;
if(min.length == 1) min = '0' + min;
timestamp.innerHTML = months[t.getMonth()] + ' ' + t.getDate() + ', ' + t.getFullYear() + ' ' + hours + ':' + min + ' ' + (pm ? 'pm' : 'am');
</script>
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