Set timezone for all DateTime returned from server

0

I'm using a backend, which returns me a DateTime by default UTC, I used the date_default_timezone_set function to set the timezone of São Paulo, but this worked only for the hours of my local server, it did not convert the ones I the backend.

I then proceeded to set for each DateTime object the timezone I need. Ex:

$createdAt->setTimeZone(new DateTimeZone("America/Sao_Paulo"));

Is there any other way for all DateTime to come with the time zone that I need?

    
asked by anonymous 07.05.2017 / 00:43

1 answer

2

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.

    
07.05.2017 / 04:35