views:

334

answers:

4

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?

A: 

Check out this. All in javascript.

reallyJim
why is this voted down?
frankadelic
Because it points at a very dubious wad of PHP/SSI/Javascript mish-mash with no further explanation.
Schwern
A: 

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.

Schwern
A: 

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>
Doug Neiner
A: 

We are using ExtJS library, which has functionalities regarding date and time which can help you a lot. As a matter of fact, on my Mozilla Firefox, it displays all dates and times according to the browsers time zone.

Nenad