Skip to content

TimeZone conversion one timeZone to another php

Last updated on July 13, 2016

PHP has very powerful date handling functions and it makes TimeZone Conversion extremely simple.

In some PHP application where we need to display date and times based on the user time Zone, to achieve this behavior we will convert and then store Date and time in the GMT format, Based on this GMT value we can again Convert date and time to Target TimeZone. actually here you no need to convert GMT format to use the method , i am converting Date time to GMT because i am storing all uses dateTimes in GMT format, its merely my preference.

I have written a function which converts one timezone into another with out fail, it is simple use and you can test it easily.

function timeZoneConvert($fromTime, $fromTimezone, $toTimezone,$format = 'Y-m-d H:i:s') {
     // create timeZone object , with fromtimeZone
    $from = new DateTimeZone($fromTimezone);
	 // create timeZone object , with totimeZone
    $to = new DateTimeZone($toTimezone);
    // read give time into ,fromtimeZone
    $orgTime = new DateTime($fromTime, $from);
	// fromte input date to ISO 8601 date (added in PHP 5). the create new date time object
    $toTime = new DateTime($orgTime->format("c"));
	// set target time zone to $toTme ojbect.
    $toTime->setTimezone($to);
	// return reuslt.
    return $toTime->format($format);
}

How to use?

Just call the function pass the parameters as required, first 3 are compulsory required, last one is optional.

      echo timeZoneConvert(date('Y-m-d H:i:s'), 'CDT', 'GMT');
 
      echo timeZoneConvert('2000-01-01 00:00:00', 'CDT', 'GMT');

by using this method you can convert to any PHP supported timeZones and function will return merely vast result.

Reference Links :

http://php.net/manual/en/class.datetime.php

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments