Difference between dates to find the number of days

Asked

Viewed 42 times

-1

Hello, friends. I have a code where I calculate the difference in days between two dates. I need to pass the variables to the object instance, but it only works if I put the string manually.

(1) This way below works:

$origin = new DateTime('2017-03-03');
$target = new DateTime('2017-04-06');
$interval = $origin->diff($target);
echo $interval->format('%R%a days');

(2) But this way below, which is what I need, does not work:

$origin = new DateTime($dataInicio);
$target = new DateTime($dataFim);
$interval = $origin->diff($target);
echo $interval->format('%R%a days');

Froma (1) returns me 34 days, but the form (2), when I pass the parameters with the same dates of (1), gives a value +209 days, gives 6 months and 26 days . How would I solve this? Can someone help me?

  • Two things: 1) their variables are actually strings? 2) If yes to the above question, their format corresponds to the necessary?

1 answer

0

What format are you receiving in the variables $dataInicio and $dataFim?

I ran this code and the account exits correctly.

$dataInicio = '2020-03-03';
$dataFim = '2020-04-06';
$origin = new DateTime($dataInicio);
$target = new DateTime($dataFim);
$interval = $origin->diff($target);
echo $interval->format('%R%a days');
  • This one you ran correctly. I get the database dates in yyyy-mm-dd format, and when I put them in $dataInicio and $datafim variables, it doesn’t work the same way. I do $dataInicio = $line['Dataincio'] and $dataFim = $line['Datafim'], but it doesn’t work.

Browser other questions tagged

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