February 24, 2011

Time Zones Hurt My Brain - One Way To Get The Time Offset

Today I needed (or at least I thought I did until I found out I didn't) to find out the difference in hours between the current user's time zone and GMT. A quick bit of searching around the internet didn't reveal anything spectacular; I found one method which involved pulling a describe on the timezone picklist and matching up the country part of it which you can get from System.userInfo(), it didn't seem ideal and involved quite a lot of code.

I realise there are various methods for getting times/dates in GMT and the local timezone and thought about how I could leverage something there to get the difference, after some fiddling and testing I came up with this:

string strOffset = System.now().format('Z'); 
string strOffsetHours = strOffset.substring(0,3); 

  strOffsetHours = strOffsetHours.substring(1); 

integer iMinutes = 100 * integer.valueOf(strOffset.substring(3)); 
double dOffset = double.valueOf(strOffsetHours + '.' + ((iMinutes) / 60));

It may seem a bit OTT but some time zones do have a half-hour or 45 minute offset in them, also the test for the + is because salesforce regards a string such as "+10" as an invalid number. Obviously the result of this code is a double representing the number of hours your are away from GMT, e.g. for where I am I get back 11.0, ergo I am eleventy hours ahead.