If the dates come in the UTC default from the external server, there is not much you can do otherwise than manually correcting like you did. Note that when creating a DateTime
object without specifying the TimeZone
, it will be considered the current server, which may not be UTC, so the ideal thing to do is:
$date = "01-05-2017 08:00:00";
$date = new DateTime($date, new DateTimeZone("UTC"));
$date->setTimeZone(new DateTimeZone("America/Sao_Paulo"));
echo $date->format('Y-m-d H:i:s'), PHP_EOL;
See working at Ideone .
If the server already has a defined timezone that is different from UTC, the result will be different. See:
// Considerando que o timezone do servidor esteja configurado:
date_default_timezone_set('America/Sao_Paulo');
$date = "01-05-2017 08:00:00";
// Data devidamente convertida de UTC para UTC-3:
$date1 = new DateTime($date, new DateTimeZone("UTC"));
$date1->setTimeZone(new DateTimeZone("America/Sao_Paulo"));
echo $date1->format('Y-m-d H:i:s'), PHP_EOL;
// Data utilizando o timezone atual do servidor:
$date2 = new DateTime($date);
$date2->setTimeZone(new DateTimeZone("America/Sao_Paulo"));
echo $date2->format('Y-m-d H:i:s'), PHP_EOL;
See working at Ideone .
Note that if your server has timezone configured for America / Sao_Paulo, the end time will be wrong if the UTC timezone is not passed as the second parameter.