javascriptdatetimetimetimezone

Displaying date/time in user's timezone - on client side


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?


Solution

  • 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>