Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting DateTime String to Different Timezones in PHP

ok i have this following codes

$from = "Asia/Manila";
$to = "UTC";
$org_time = new DateTime("2012-05-15 10:50:00");
$org_time = $org_time->format("Y-m-d H:i:s");
$conv_time = NULL;

$userTimezone = new DateTimeZone($from);
$gmtTimezone = new DateTimeZone($to);
$myDateTime = new DateTime($org_time, $gmtTimezone);
$offset = $userTimezone->getOffset($myDateTime);
$conv_time = date('Y-m-d H:i:s', $myDateTime->format('U') + $offset);
echo $conv_time;

with this code i want to convert 2012-05-15 10:50:00 to UTC and -8 Timezone(I used America/Vancouver) but it gives me a strange results

Asia/Manila > UTC  
2012-05-15 19:50:00 = the correct is 2012-05-15 02:50

and for America/Vancouver

Asia/Manila > America/Vancouver 
2012-05-16 02:50:00 = the correct is 2012-05-14 19:50

where I went wrong?

like image 924
Netorica Avatar asked May 15 '12 02:05

Netorica


People also ask

How do you change from one time zone to another?

To convert a ZonedDateTime instance from one timezone to another, follow the two steps: Create ZonedDateTime in 1st timezone. You may already have it in your application. Convert the first ZonedDateTime in second timezone using withZoneSameInstant() method.

What is UTC timezone PHP?

The default timezone for PHP is UTC regardless of your server's timezone. This is the timezone used by all PHP date/time functions in your scripts. To change the PHP timezone for an app, create a .user.ini file in the app's public directory with the following contents: date.timezone = America/Los_Angeles.

How can I get timezone in PHP?

The date_default_timezone_get() function returns the default timezone used by all date/time functions in the script.

What is the default timezone in PHP?

If none of the above succeed, date_default_timezone_get() will return a default timezone of UTC .


Video Answer


1 Answers

You are making things way too hard. To convert between time zones, all you need to do is create a DateTime object with the proper source time zone, and then set the destination time zone via setTimeZone().

$src_dt = '2012-05-15 10:50:00';
$src_tz =  new DateTimeZone('Asia/Manila');
$dest_tz = new DateTimeZone('America/Vancouver');

$dt = new DateTime($src_dt, $src_tz);
$dt->setTimeZone($dest_tz);

$dest_dt = $dt->format('Y-m-d H:i:s');
like image 96
Matthew Avatar answered Sep 30 '22 11:09

Matthew