Dealing with time zones can cause some real pains. As a result when storing a date/time in an application it is standard to store the date/time as GMT. This makes it easier on the application in comparing dates, but isn’t very friendly for users. The next step is for an applications to provide an option to indicate what time zone dates should be displayed as. But what if we could skip that step and detect what time zone the client is in automatically? Turns out Javascript can help out here. The Date object has access to the time zone offset, here’s a simple function to get the number of hours the browser is plus or minus from GMT:
[sourcecode lang=”javascript”]
function get_time_zone_offset( ) {
var current_date = new Date( );
var gmt_offset = current_date.getTimezoneOffset( ) / 60;
return gmt_offset;
}
[/sourcecode]
The getTimezoneOffset method of the Date object returns the difference in minutes from GMT, so dividing by 60 gives us the offset in hours. By grabbing the offset as part of a login form you can detect the time zone offset for each user automatically. An example HTML snippet might help make this more clear:
[sourcecode lang=”javascript”]
<p>
Time Zone offset: <span id="offset"></span>
</p>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
function get_time_zone_offset( ) {
var current_date = new Date( );
var gmt_offset = current_date.getTimezoneOffset( ) / 60;
return gmt_offset;
}
$(‘#offset’).html( get_time_zone_offset( ) );
</script>
[/sourcecode]
Save that as an HTML file, load it into your browser and it will show you what it detected for your time zone offset. If you do decide to use this as part of your login form be sure to filter it for only valid values. Never blindly trust data from a web browser. Keep in mind that it can be a negative number and a have decimal values (for those areas that don’t use whole hour offsets for their time zone).