Jaylen
Jaylen

Reputation: 40371

DateTime class if not displaying the correct data

I am using DateTime class for the first time to convert between different time zones.

Here is what I have

$USER_TIME_ZONE = new DateTimeZone('America/Los_Angeles');
$UTC = new DateTimeZone('UTC');
$schedule_date = new DateTime($call['triggerOn'], $USER_TIME_ZONE);
echo $schedule_date->format('m/d/Y h:i A');

$schedule_date = new DateTime($call['triggerOn'], $UTC);
echo $schedule_date->format('m/d/Y h:i A');

Here is how I am going through my result and trying to convert them

foreach ( $activities AS $call){ 
    $USER_TIME_ZONE = new DateTimeZone('America/Los_Angeles');
    $UTC = new DateTimeZone('UTC');
    $schedule_date = new DateTime($call['triggerOn'], $UTC);
    echo $schedule_date->format('m/d/Y h:i A');
 }

The following are value for $call['triggerOn']

2013-02-27 18:00:37
2013-02-02 01:11:07
2013-01-10 17:12:14
2013-02-27 22:29:42
2013-02-27 22:28:38
2013-02-25 21:53:12
2013-02-14 14:35:48
2012-12-13 14:03:16
2013-03-04 19:04:20
2013-03-01 18:52:48
2013-03-05 15:46:56
2013-03-11 15:26:17
2013-02-07 18:17:30
2013-03-05 18:04:25

Both of my outputs are the same! I don't understand why. Is there a configuration that I need to do on the server side as I have PHP running on Windows Server 2008 R2. Thank you for your help and time.

Upvotes: 1

Views: 88

Answers (2)

tbcrowe
tbcrowe

Reputation: 15

The DateTime::format() method is returning the time in the timezone the data was created in. There's no conversion going on. Thus your output times are going to be the same as your input times regardless of the timezone you pass in. You can verify this by adding an 'e' to the format parameter. You will see that in the first case the timezone is America/Los_Angeles and in the second it is UTC.

You're probably trying to convert the time between timezones, right? In order to do that just create a single new DateTime object in one timezone, call the setTimezone method with the second timezone, and then format the result.

All of this assumes that the $call['triggerOn'] value is neither a timestamp nor a value with the timezone identified. In that case the second parameter of the DateTime constructor is ignored.

Upvotes: 1

BIT CHEETAH
BIT CHEETAH

Reputation: 1200

Knowing the value of $call['triggerOn'] would help, but would this work:

$USER_TIME_ZONE = 'America/Los_Angeles';
$UTC = 'UTC';
$schedule_date = new DateTime( $call['triggerOn'], $USER_TIME_ZONE );
echo $schedule_date->format( 'm/d/Y h:i A' );

$schedule_date = new DateTime( $call['triggerOn'], $UTC );
echo $schedule_date->format( 'm/d/Y h:i A' );

Basically, instead of creating new DateTime objects to use as parameters for other new DateTime objects, what if you just use the timezone string instead? Does that work?

Upvotes: 0

Related Questions