UTC Date/Time String to Timezone
How do I convert a date/time string (e.g. 2011-01-01 15:00:00) that is UTC to any given timezone php supports, such as America/New_York, or Europe/San_Marino.
Solution 1:
PHP's DateTime
object is pretty flexible.
$UTC = new DateTimeZone("UTC");
$newTZ = new DateTimeZone("America/New_York");
$date = new DateTime( "2011-01-01 15:00:00", $UTC );
$date->setTimezone( $newTZ );
echo $date->format('Y-m-d H:i:s');
Solution 2:
PHP's DateTime
object is pretty flexible.
Since the user asked for more than one timezone option, then you can make it generic.
Generic Function
function convertDateFromTimezone($date,$timezone,$timezone_to,$format){
$date = new DateTime($date,new DateTimeZone($timezone));
$date->setTimezone( new DateTimeZone($timezone_to) );
return $date->format($format);
}
Usage:
echo convertDateFromTimezone('2011-04-21 13:14','UTC','America/New_York','Y-m-d H:i:s');
Output:
2011-04-21 09:14:00
Solution 3:
Assuming the UTC is not included in the string then:
date_default_timezone_set('America/New_York');
$datestring = '2011-01-01 15:00:00'; //Pulled in from somewhere
$date = date('Y-m-d H:i:s T',strtotime($datestring . ' UTC'));
echo $date; //Should get '2011-01-01 10:00:00 EST' or something like that
Or you could use the DateTime object.
Solution 4:
function _settimezone($time,$defaultzone,$newzone)
{
$date = new DateTime($time, new DateTimeZone($defaultzone));
$date->setTimezone(new DateTimeZone($newzone));
$result=$date->format('Y-m-d H:i:s');
return $result;
}
$defaultzone="UTC";
$newzone="America/New_York";
$time="2011-01-01 15:00:00";
$newtime=_settimezone($time,$defaultzone,$newzone);