Warning: Division by zero with dates

Asked

Viewed 49 times

-1

how can I calculate a date range for example: 24/08/2017 and 09/05/2017 and take 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);
  • this sum and the total value in days as I mentioned in the example 24/08/2017 and 09/05/2017 the total value in days of those dates and 106 days. intendeu? Voce will add the first date that and 09/05/2017 with 24/08/2017 and the value that will come out and 106 days

  • how do I do what I want you would know me?

  • I’ve already edited the answer.

1 answer

2


The mistake happens because you are using $diasC as 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, this division will result in a value between 0 and 1. Using floor and doing the cast type for 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 class DateTime. 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 exit would be:

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

Even if you reverse the order of the dates, the result is the same. If this is in comparison to some other specification of your application, take care.

See working on Ideone.

If it is necessary to get it on calendar days, not months and years, just format the result using %a:

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

See working on Ideone.

Note: Obtaining numerical value

To get only the numerical value, just do:

$diffInDays = (int) $diff->format("%a");
  • it is set yes and the final date coming from the database I forgot to put it here I will edit the question

  • edited the question

  • exactly that thank you very much

Browser other questions tagged

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