How to leave the negative operator after using diff () in php

2

Good afternoon. I do not know if it was very clear but the following, date_diff() , the problem is what, when I convert the interval $intervalo = date_interval_format($resultado, '%a') if the result is less than 0 the number is positive, and is disturbing my logic, when the deadline is in arrears, I can identify, but when I make the difference and is delayed 30 days (-30), my code is interpreting that it is missing 30 days, because it is positive. how can I solve it, code below:

$database = date_create($row['expira']);
$datadehoje = date_create();
$resultado = date_diff($database, $datadehoje);
$intervalo = date_interval_format($resultado, '%a');
echo $intervalo;
    
asked by anonymous 23.12.2018 / 18:24

1 answer

3

The result of the comparison is always the number of days but there is an attribute in the object returned by date_diff() called invert indicating whether the value is positive or negative (zero for positive numbers and one for negative) p>

<?php

    $primeiraData = date_create('2018-12-01');
    $segundaData = date_create('2018-12-31');

    $intervalos[0] = date_diff($primeiraData, $segundaData);
    $intervalos[1] = date_diff($segundaData, $primeiraData);

    foreach ($intervalos as $intervalo){
        $diferenca = (int)$intervalo->format('%R%a');
        echo "'Diferença de " . $diferenca . " dias (" . $intervalo->invert . ")'\n";
    }
?>

Running the program it will display this:

'Diferença de 30 dias (0)'
'Diferença de -30 dias (1)'

If you only want to display the number of days on the screen you can use the% R in the formatting of the value but if you want to work with this value in some calculation you will need to use the% to change the signal.

    
23.12.2018 / 19:05