Error of calculating days interval between two dates using diff in PHP

Asked

Viewed 89 times

1

I am having a difference of values when calculating the interval of days between two dates. I have the following:

$data1 = new DateTime('2019-06-10');
$data2 = new DateTime('9999-12-31');

If I use the following command I have a value:

echo $intervalo->format('%a');

This shows on the screen: 2914797.

But in case I use:

echo $intervalo->d;

I have the value of: 21.

Is it right to use the first form? Or is something wrong in the second form of calculating the interval of days?

1 answer

3


When calculating the difference between two dates using DateTime::diff, the result is a DateInterval, and this class "breaks" the difference in several fields (years, months, days, etc). To better understand, see the example below:

$data1 = new DateTime('2019-06-10');
$data2 = new DateTime('9999-12-31');
$intervalo = $data1->diff($data2);
echo $intervalo->format('%y anos, %m meses, %d dias');

The exit is:

7980 anos, 6 meses, 21 dias

The formats %y, %m and %d correspond respectively to the fields y, m and d of DateInterval. That is, the code below generates the same output as the previous example:

// 7980 anos, 6 meses, 21 dias
echo $intervalo->y . ' anos, ' . $intervalo->m . ' meses, ' . $intervalo->d . ' dias';

Already the format %a brings the total of days corresponding to this duration (in this case the total of days corresponding to 7980 years, 6 months and 21 days). See all formats available on documentation.

So if you want to know the total amount of days, use the format %a (or call directly $intervalo->days). If you want the difference properly "broken" in years, months and days, use the fields y, m and d (or the formats %y, %m and %d).

Browser other questions tagged

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