Why does date_diff count my date range wrong?

7

In my code:

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 total daily $ gives 1, not 2 as I expected ... Why does this occur?

    
asked by anonymous 10.09.2014 / 20:24

2 answers

7

As pointed out by @ lost in the comments, this is a bug in php. To help fix the problem I recommend that all date calculations in php be made using UTC. This would look something 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 you need to output the data, you can change the timezone with the DateTime :: setTimeZone ()

$meuTimeZone = new DateTimeZone('America/Sao_Paulo');
$DataEntrada->setTimeZone($meuTimeZone);
echo $DataEntrada->format('d/m/Y H:i:s');
    
10.09.2014 / 22:08
3

Just adding the @Kaminary response, which was super useful for my system, in the sense that I could solve this bug easily by placing the:

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

Just below the POST entries that came via XHR from AJAX communication.

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 is a test case to evolve the language in the next versions. PHP is a poorly typed but widely used language, easy to learn and with great support on the internet (mainly in English). It's even the one I like the most I've ever used.

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

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

    
28.09.2014 / 19:38