Brett
Brett

Reputation: 20079

Having issue getting correct time output using DateTime when changing timezones

Please see this code:

// Instantiate DateTime object with users timezone
$date = new \DateTime(null, new \DateTimeZone(Yii::$app->formatter->timeZone));     

// Get current year     
echo $date->format('l, F j Y g:i:s A');

echo "<br>\n";

/* Get year the event took place */

// Change the timezone to the timezone we will be giving it a unix timestamp in
$date->setTimezone(new \DateTimeZone(Yii::$app->formatter->defaultTimeZone));

$utc_time = time() - date('Z');
$utc_time = strtotime('- 1 Year', $utc_time);

// Update our time
$date->setTimestamp($utc_time);

// Now change the timezone back to the users timezone
$date->setTimezone(new \DateTimeZone(Yii::$app->formatter->timeZone));

// Get year the thread was started in...
echo $date->format('l, F j Y g:i:s A');

Yii::$app->formatter->defaultTimeZone is set to UTC and the reason we are changing to that is because the timestamp we are passing to it will be coming from the database in UTC, which is stored in the database by doing something like:

time() - date('Z')

The above will output something like:

Saturday, August 29 2015 11:28:54 PM
Friday, August 29 2014 3:28:54 PM

As you can see the second time output is incorrect (the hours aren't right).

What I am trying to do is get the current hear (works) and then get the year from the unix timestamp which we will be retrieving from the database; but as stated above this year will be returned as UTC and hence needs to be converted back to the users timezone somehow.

What am I doing wrong here?

Upvotes: 0

Views: 47

Answers (1)

user2480047
user2480047

Reputation:

As proposed via comments, here you have a function I use to convert date/time between different timezones:

function convert_time($cur_time, $tz_name_ini, $tz_name_res)
{
    $tz1 = new DateTimeZone($tz_name_ini); 
    $tz2 = new DateTimeZone($tz_name_res); 
    $dt1 = new DateTime("now", $tz1);
    $dt2 = new DateTime("now", $tz2);

    $offset1 = $tz1->getOffset($dt1);
    $offset2 = $tz2->getOffset($dt2);
    $diff_offset = $offset2 - $offset1;

    return date("l, F j Y g:i:s A", $cur_time + $diff_offset);
}

For example, if my server is in Denver and I want the application to show the time in Madrid, I would call the function as follows:

$tz_name_ini = "America/Denver";
$tz_name_res = "Europe/Madrid";
convert_time(time(), $tz_name_ini, $tz_name_res);

List with all the supported timezones: http://php.net/manual/en/timezones.php

Upvotes: 1

Related Questions