Skip to content

Automatic timezone conversion with JavaScript

September 3, 2010

Timezones are a pain to deal with as a programmer but our server monitoring service, Server Density, has handled them for some time. It requires you to select your timezone from your profile and we then adjust the times appropriately. It still requires an action on the user’s part so over the last few weeks we’ve been running a test on the dashboard to use JavaScript to automatically convert the timestamps we store in our database in GMT/UTC, to the time of the local system browser.

Triggered Alerts

This means that if you change the timezone of your system and reload the dashboard (you may need to restart your browser), the timezone will automatically be detected and the right date/time displayed for you. This is particularly useful if you travel a lot, or have different computers in different timezones that you move between. Its also removes an unnecessary setting.

The code behind the conversion

The conversion has to be done from a UTC/GMT timestamp so if you view source on the dashboard you’ll see that we output a full RFC 2822 formatted date. This includes the timezone and can be anything that can be parsed by the JavaScript Date method. This is contained inside an HTML span tag so we can extract it in the JS later:

<span class="convertTimestamp">Fri, 03 Sep 2010 09:36:45 +0000</span>

This is then picked up on page load by a JQuery $(document).ready() call to our conversion method. Now our code includes some formatting fluff to make the output useful but the raw code that does the conversion is extremely simple.

You first read the timestamp into a Date object:

var utcDate = new Date("Fri, 03 Sep 2010 09:36:45 +0000");

And then you just call the output methods to display the parts you want. E.g.

document.write(utcDate.getDate());

would output 3 because we passed in the date 3rd Sept. But depending on your timezone this would be converted to your local date when it’s output. And that’s it! We’ve tested in the latest versions of Chrome, Firefox, Safari and Mobile Safari on the iPad and iPhone, and they all convert to the local timezone.

Our full conversion code

The Date methods aren’t 100% useful for outputting a nicely formatted date, so we do a small amount of formatting ourselves. This code is contained within a JS file and gets included on pages we want to the conversion on. It looks for timestamps inside a span with the class convertTimestamp and it requires JQuery.

We’re releasing this under the FreeBSD license like our monitoring agents, so you can do what you like with it.

var DateFormatting = {

	init: function()
	{
		var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
		
		// Loop over and write in the date formatted using the local 
		$('span.convertTimestamp').each(function()
		{			
			var utcDate = new Date($(this).html());
			
			// Add leading zeros
			// Hours
			var hours = new String(utcDate.getHours());

			if (hours.length == 1)
			{
				hours = '0' + utcDate.getHours();
			}
			
			// Minutes
			var minutes = new String(utcDate.getMinutes());
			
			if (minutes.length == 1)
			{
				minutes = '0' + utcDate.getMinutes();
			}
			
			// Seconds
			var seconds = new String(utcDate.getSeconds());
			
			if (seconds.length == 1)
			{
				seconds = '0' + utcDate.getSeconds();
			}
			
			$(this).html(utcDate.getDate() + ' ' + months[utcDate.getMonth()] + ' ' + utcDate.getFullYear() + ' ' + hours + ':' + minutes + ':' + seconds);
		});
	},
}

$(document).ready(DateFormatting.init);

One Comment leave one →
  1. September 25, 2010 9:27 pm

    David –

    Worth noting that the time displayed is not necessarily the time that it *was* in your time zone at the date referred to, due to changes in DST over the course of a year and DST policy over much longer periods.

    For example, during the second world war, Britain observed GMT+1 in winter, and GMT+2 in summer, whilst today we observe GMT in winter and GMT+1 in summer. So if at say, 2pm on the 23rd of July 1944 my server (a Colossus, obviously) went down, and server density recorded the fault, you would have recorded “1944-07-23 12:00:00″ UTC. If I were to view that time now, I’m still in the same location, same time zone, still in summer time, but due to changes in government policy, that same time zone is now at GMT+1, not GMT+2, so you’d now display that the server went down at 1pm.

    Obviously there’s an argument that this is the correct behaviour, and it’s certainly simpler than the alternative, which necessitates server-side processing and the TZ database. Sadly, I normally take the view that DST needs to be taken into account. The time displayed should reflect the offset from UTC that would have been in effect in the user’s timezone at the actual time of the timestamp, not the offset in effect now.

    Fortunately, few people were operating servers in 1944. But some countries still faff with DST policy on a fairly regular basis, and Britain last changed its mind in the 90s iirc. :-)

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

Please log in to WordPress.com to post a comment to your blog.

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 902 other followers