PHP DateTime :: diff Problem with DateTime :: format

When I try to format the date difference using normal PHP codes (d, Y, m, etc.) for dates and times, it just outputs the letter instead of the value. This only happens when I format the DateTime :: diff. It works great with a simple DateTime object.

It:

$date1 = new DateTime('2000-01-01');
$date2= new DateTime('now');
$date=$date2->diff($date1);
echo $date->format('d days ago');

      

Displays "d days ago".

I know that if I replace d with% a it will output how many days ago it was. I was wondering what kind of seconds, minutes or even years will be displayed for other characters.

Thanks in advance!

+3


source to share


1 answer


DateTime :: diff () returns a DateInterval object .

For example:

<?php

$date1 = new DateTime('2000-01-01');
$date2= new DateTime('now');
$interval=$date2->diff($date1);
echo "Years: {$interval->y }\n";
echo "Months: {$interval->m }\n";
echo "Days: {$interval->d }\n";
echo "Hours: {$interval->h }\n";
echo "Mins: {$interval->i }\n";
echo "Secs: {$interval->s }\n";
echo $interval->format("%Y years, %m months, %d days,  %H hours, %i minutes, %s seconds") . "\n";

      



The output will be:

Years: 13
Months: 1
Days: 11
Hours: 13
Mins: 14
Secs: 44
13 years, 1 months, 11 days,  13 hours, 21 minutes, 43 seconds

      

+7


source







All Articles