Converting Timestamps to Zone Offsets In PHP

As the title is probably a misleading summary - this post is about how to convert a unix timestamp, eg 1234199936 to a localized version of that stamp using an offset like +5 hours, or have it parsed and displayed as a human readable time/date.

I encountered a need for this whilst coding SimpleStats, and feel that there is no other function out there that doesn't have any dependencies, and calculates the new time in a purely mathematical and easy to understand way.

I wanted to record hits into the SimpleStats database according to the server's local time, which happens to be EST (GMT-5). Originally my idea was to enforce a date_default_timezone_set() on each page that displayed a localized time to the user, but this wasn't an ideal solution, as I was getting different results using different date functions, probably due to my own code being wrong.

I decided to scrap that idea, and convert the server's local timestamp stored in the hit database into the user's local time offset after the data was pulled from the database. To do that, I used a simple algorithm that calculates the number of seconds the user's timezone varies from the servers', then subtracted or added it to the timestamp stored in the database.

The function behaves exactly the same as PHP's date() function, except it requires an extra parameter - the offset value.

function local_date($format = 'U',$offset = '0',$stamp = ''){
  if(empty($stamp)){$stamp = time();}
  $result = $stamp+(3600*$offset);
  $end = date($format,$result);
  return $end;
}

To use the function, you would call it like you would the date() function, except using the extra $offset string. As with the date() function the timestamp can be omitted, making the function convert the server's local time.

local_date($formatting,$offset,$timestamp);

The below example uses the current time, and adds 5 hours onto it. This could be used for example to convert a server-side EST time value to GMT.

local_date('l jS \of F Y h:i:s A','+5');

This would result in something like Monday 8th of August 2005 03:12:46 PM, if the server time at that moment was Sunday 7th of August 2005 22:12:46 PM.

Another example, using a unix timestamp for conversion:

local_date('U','-3','1234199936');

This would result in the timestamp 1234189136, which is 3 hours behind the timestamp pumped into the function above.

This function seems a lot simpler than messing with the built in date features of PHP, and I know that it will do exactly what I want with no exceptions.

blog comments powered by Disqus Powered by Disqus