PHP function to convert time from one timezone to another

Some applications require finding out what the current time would be in a particular timezone. Another similar requirement would be to convert a given date/time value to a different timezone.

PHP has very powerful date handling functions and it makes the above very simple and easy. We have tried to use quite a few readymade timezone conversion classes but either they had a bug or they were too complicated. Hence we came up with our own class. The actual conversion code is only about 4 lines of code.

What it does is convert the time string argument from the source timezone into GMT time and then convert into the target timezone. This approach was far simpler than trying to directly convert from source timezone into the target timezone.

class convert_timezone
{
	function convert_timezone() // Constructor of the class
	{
	}

	function conver_to_time($conv_fr_zon=0,$conv_fr_time="",$conv_to_zon=0)
	{
		//echo $conv_fr_zon."<br>";
		$cd = strtotime($conv_fr_time); 
		
		$gmdate = date('Y-m-d H:i:s', mktime(date('H',$cd)-$conv_fr_zon,date('i',$cd),date('s',$cd),date('m',$cd),date('d',$cd),date('Y',$cd))); 
		//echo $gmdate."<br>";
				
		$gm_timestamp = strtotime($gmdate);
		$finaldate = date('Y-m-d H:i:s', mktime(date('H',$gm_timestamp )+$conv_to_zon,date('i',$gm_timestamp ),date('s',$gm_timestamp ),date('m',$gm_timestamp ),date('d',$gm_timestamp ),date('Y',$gm_timestamp ))); 
		
		return $finaldate;
	}
}

Example usage would be:

$c = new convert_timezone();

$resultTime = $c->conver_to_time(5.30, “2011-05-09 11:00:00”, -13);

$resultTime = $c->conver_to_time(-4, “2011-05-09 11:00:00”, 10);

The first one converts 5th May, 2011, 11 am from the timezone GMT+0530hrs to GMT-1300hrs

The second one coverts 5th May,2011 11 am from the timezone GMT-0400hrs to GMT1000 hrs

1 Comment

  1. We have daylight saving in New Zealand so it changes between +12 in winter and +13 in summer, so we’re using date(‘Z’) to get the offset in seconds from server time, convert it to hours and then using the result (either +12 or +13) in the convert_timezone function.

2 Trackbacks / Pingbacks

  1. abcphp.com
  2. PHP function to convert time from one timezone to another « Freedom To Learn ……….

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.