Friday, 19 April 2019

Handling timezone conversion with PHP DateTime

Handling timezone conversion with PHP DateTime

Create function

function convert_to_server_datetime($date, $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
{
    try {
        $dateTime = new DateTime ($date, new DateTimeZone($userTimeZone));
        $dateTime->setTimezone(new DateTimeZone($serverTimeZone));
        return $dateTime->format("Y-m-d H:i:s");
    } catch (Exception $e) {
        return '';
    }
}

Example:

$userDate = '2019-04-19 13:20:00';

echo convert_to_server_datetime($userDate);

Other Method

public function convert($clienttimezone = null, $servertimezone = null){
$clientz=timezone_open("$clienttimezone");
$serverdateTime=date_create("now",timezone_open("$servertimezone"));
$offset1 = timezone_offset_get($clientz,$serverdateTime);
$servertz=timezone_open("$servertimezone");
$clientdateTime=date_create("now",timezone_open("$clienttimezone"));
$offset2 = timezone_offset_get($servertz,$clientdateTime);
if(($offset1 > 0 && $offset2 < 0) || ($offset1 < 0 && $offset2 < 0) || ($offset1 < 0 && $offset2 > 0)){
$offset = $offset1 -($offset2);
}else {
$offset = $offset1 +($offset2);
}
return $offset;
//return sprintf( "%s%02d:%02d", ( $offset >= 0 ) ? '+' : '-', abs( $offset / 3600 ), date("i",abs( $offset % 3600 )) );
}

Example
$clienttimezone = "Europe/Paris";
$servertimezone = date_default_timezone_get();

$timediff =  convert($clienttimezone,$servertimezone);
$transfer_date = '2019-04-20 20:04:05';

echo date('d M Y, h:i a',strtotime($transfer_date)+$timediff);

0 comments:

Post a Comment