简体   繁体   中英

How to convert datetime by applying UTC offset in php?

how to apply the UTC in datestring in php?

Sample Code:

$sample_date = "2016-01-01 01:00:00 +01:00";

How to convert this one to:

$sample_date = "2016-01-01 02:00:00";

One way to be to write a custom function as below:

$thisDate = "2016-01-01 01:00:00 +01:00";
$seperated = explode('+', $thisDate);

$splitHours = explode(':',$seperated[1]);

$hoursToAdd = isset($splitHours[0]) ? (($splitHours[0]!='0' && $splitHours[0]!='00') ? $splitHours[0].'H' : '') : '';
$minutesToAdd = isset($splitHours[1]) ?  (($splitHours[1]!='0' && $splitHours[1]!='00') ? $splitHours[1].'S' : '') : '';

$addtionString = ($splitHours[0]!='' || $splitHours[1]!='') ? 'PT'.$hoursToAdd.$minutesToAdd : '';
$date = new DateTime($seperated[0]);
if($addtionString != '') {
    $date->add(new DateInterval($addtionString));

}
echo $date->format('Y-m-d H:i:s') . "\n";

Can't think of any built in function which already does it..

You will get result below

$date = date('Y-m-d H:i:s',(strtotime($sample_date)+3600));                    
echo $date; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM