PHP function to convert time from one timezone to another

Hi ,

I found PHP function which is very useful for time  conversion. I got this from http://truelogic.org/wordpress/2011/05/22/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.

 

The first call to function converts 14 Sep, 2011, 02 am from the my timezone GMT+0530hrs to GMT-600hrs
here I am passing my time zone i.e. +5.30— my current time & date in format(2011-0-14 02:00:00)here
the time in 24hours– last parameter to which time zone you want to convert..here I put
the timezone of Texa-USA i.e. -6
After running the program.. I got result as ‘2011-09-14 02:00:00’.

 

<?php

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;
  }
}

$resultTime = $c->conver_to_time(5.30, "2011-09-14 02:00:00", -6);
echo $resultTime;

?>
Advertisements

PHP Developer..

Posted in PHP

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: