Why does date_diff count my date range wrong?

Asked

Viewed 181 times

7

In that code of mine:

date_default_timezone_set('America/Sao_Paulo');
$DataEntrada = new DateTime('19-10-2014');//data no formato d-m-Y
$DataSaida = new DateTime('21-10-2014');

$interval = date_diff($DataSaida, $DataEntrada);
$totalDiarias = $interval->days;

echo $totalDiarias;

The $totalDiarias gives 1, not 2 as I expected... Why this occurs?

  • Which php version do you use?

  • 1

    php version 5.3

  • Seems to be some bug this question has several links related, rs if you remove the time zone it returns 2.

2 answers

7


As pointed out by @lost in the comments, this is a bug in php. To help solve the problem I recommend that all date calculations in php be done using UTC. That way it would look like:

$DataEntrada = new DateTime('19-10-2014', new DateTimeZone('UTC'));
$DataSaida = new DateTime('21-10-2014', new DateTimeZone('UTC'));

$interval = date_diff($DataSaida, $DataEntrada);
$totalDiarias = $interval->days;

echo $totalDiarias;

When there is need to output the data, you can change the Timezone with the function Date::setTimeZone()

$meuTimeZone = new DateTimeZone('America/Sao_Paulo');
$DataEntrada->setTimeZone($meuTimeZone);
echo $DataEntrada->format('d/m/Y H:i:s');
  • Thanks @Kaminary helped too much !

  • @Hamiltoncarmisinjunior, mark as settled the question :)

3

Just adding the reply from @Kaminary, which was super useful for my system, in the sense that I could fix this bug easily by putting the:

$meuTimeZone = new DateTimeZone('America/Sao_Paulo');

Just below the POST entries arriving via XHR from communication with AJAX.

It is important to note that some Bugs like this are normal in all programming languages and it is essential to share this, as this serves as a test case to evolve the language in the next versions. PHP is a weakly typed but widely used language, easy to understand and with great support on the Internet (mainly in English). It’s even the one I like the most among the ones I’ve used.

According to the links of @lost in the comments of the question this should be solved in the next versions of PHP.

For systems, or part of systems, more critical recommend the use of ADA for example.

Browser other questions tagged

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