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

Asked

Viewed 153 times

2

Good afternoon. I do not know if it was very clear but the following, use 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, because I need that when the deadline is in delay, I can identify, only that when I make a difference and is late 30 days (-30), my code is interpreting that is missing 30 days, for it is positive. how can I solve, code below:

$database = date_create($row['expira']);
$datadehoje = date_create();
$resultado = date_diff($database, $datadehoje);
$intervalo = date_interval_format($resultado, '%a');
echo $intervalo;

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).

<?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 will display this:

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

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

Browser other questions tagged

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