Warning: Division by zero with dates

-1

How can I calculate a range of dates, for example: 08/24/2017 and 09/05/2017 and get the total amount of days?

For example the result of this difference would have to give 106 days difference from one date to another

code:

$data = $row['data'];
$data_inicio = $row['data_inicio'];

$now = time();
$date1 = date("Y-m-d", $now);

$time_inicial = geraTimestamp($date1);
$time_final = geraTimestamp($data);
$diferenca = $time_final - $time_inicial;

$dias = (int)floor($diferenca / (60 * 60 * 24));



$d2 = geraTimestamp($data_inicio);
$diff =  $time_inicial - $d2;

$diasC = (int)floor($diff / (60 * 60 * 24));


$conta = ($dias * 100) / $diasC;                                                                


$result = number_format($conta,2);
    
asked by anonymous 09.05.2017 / 23:07

1 answer

2

The error happens because you are using $diasC as the denominator. The value of this variable is defined in the previous line:

$diasC = (int) floor($diff / (60 * 60 * 24));

That is, if the difference between the dates is less than one day, that division will result in a value between 0 and 1. Using floor and casting type to int the result will be 0. Using denominator 0 is not allowed. Either you validate the value of this variable to be greater than zero or you use the solution below.

Solution

If the goal is just to get the difference between dates, use the native DateTime class. It has a method called diff that calculates the difference between two dates. See:

$data1 = new DateTime("2017-05-12");
$data2 = new DateTime("2017-05-09");

$diff = $data1->diff($data2);

echo $diff->format("Diferença de %y anos, %m meses e %d dias."), PHP_EOL;

The output would be:

Diferença de 0 anos, 0 meses e 3 dias.

Even if you reverse the order of dates, the result is the same. If this is in contrast to some other specification of your application, be careful.

  

See working at Ideone .

If you need to get in days, not months and years, just format the result using %a :

echo $diff->format("Diferença de %a dias corridos."), PHP_EOL;
  

See working at Ideone .

Note: Getting numeric value

To get only the numeric value, just do:

$diffInDays = (int) $diff->format("%a");
    
09.05.2017 / 23:31