Set Timezone for all Datetime returned from server

Asked

Viewed 204 times

0

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

I then set for each Datetime Object the Timezone I need. Ex:

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

Is there any other way for everyone DateTime come with the time zone I need?

  • You cannot use the function date_default_timezone_set also in your backend?

  • @Andersoncarloswoss the backend is third party

  • So it’s just the way you did it anyway.

1 answer

2


If the dates come in the UTC standard of the external server, there is not much you do but manually correcting as you did. Remember that when creating an object DateTime without specifying the TimeZone, will be considered the current server, which may not be UTC, therefore, the ideal 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 on Ideone.

If the server already has a Timezone defined 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 on Ideone.

Note that if your server has Timezone configured for America/Sao_paulo, the final time will be wrong if you do not pass the Timezone for UTC as the second parameter.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.