Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert between time zones in PHP using the DateTime class?

I am trying to convert time between current time to UTC and UTC to current time zone.

Here is what I have done:

$schedule_date = new DateTime($triggerOn, new DateTimeZone('UTC') ); $triggerOn =  $schedule_date->format('Y-m-d H:i:s');  echo $triggerOn; 

The output value does not change the only thing that changes in format.

the string $triggerOn was generated based on America/Los_Angeles timezone

This is how my string looks like before and after:

BEFORE    04/01/2013 03:08 PM AFTER     2013-04-01 15:08:00 

So the issue here is that DateTime does not convert to UTC.

like image 891
Jaylen Avatar asked Mar 25 '13 22:03

Jaylen


People also ask

How do I convert one time zone to another in php?

php $date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru')); echo $date->format('Y-m-d H:i:sP') . "\n"; $date->setTimezone(new DateTimeZone('Pacific/Chatham')); echo $date->format('Y-m-d H:i:sP') .

How do I convert datetime to another time zone?

When you send the database time to user, convert it to the correct timezone using timeInfo . DateTime userTime = TimeZoneInfo. ConvertTimeFromUtc(dbDateTime, timeInfo);


2 Answers

What you're looking for is this:

$triggerOn = '04/01/2013 03:08 PM'; $user_tz = 'America/Los_Angeles';  echo $triggerOn; // echoes 04/01/2013 03:08 PM  $schedule_date = new DateTime($triggerOn, new DateTimeZone($user_tz) ); $schedule_date->setTimeZone(new DateTimeZone('UTC')); $triggerOn =  $schedule_date->format('Y-m-d H:i:s');  echo $triggerOn; // echoes 2013-04-01 22:08:00 
like image 172
Mike Avatar answered Oct 05 '22 23:10

Mike


You are consuming the date/time and setting the time zone correctly, however before formatting the datetime, you are not setting the desired output timezone. Here is an example which accepts a UTC time zone, and converts the date/time to the America/Los_Angeles time zone:

<?php $original_datetime = '04/01/2013 03:08 PM'; $original_timezone = new DateTimeZone('UTC');  // Instantiate the DateTime object, setting it's date, time and time zone. $datetime = new DateTime($original_datetime, $original_timezone);  // Set the DateTime object's time zone to convert the time appropriately. $target_timezone = new DateTimeZone('America/Los_Angeles'); $datetime->setTimeZone($target_timezone);  // Outputs a date/time string based on the time zone you've set on the object. $triggerOn = $datetime->format('Y-m-d H:i:s');  // Print the date/time string. print $triggerOn; // 2013-04-01 08:08:00 
like image 26
Joshua Burns Avatar answered Oct 06 '22 00:10

Joshua Burns