How can PHP users efficiently format and display date differences in various units (years, months, weeks, days)?

To efficiently format and display date differences in various units such as years, months, weeks, and days in PHP, you can use the DateTime class along with DateInterval to calculate the difference between two dates. You can then extract the individual components (years, months, days) from the DateInterval object and format them as needed for display.

$date1 = new DateTime('2021-01-01');
$date2 = new DateTime('2022-03-15');

$interval = $date1->diff($date2);

$years = $interval->y;
$months = $interval->m;
$weeks = floor($interval->days / 7);
$days = $interval->days % 7;

echo "Difference: ";
echo "$years years, $months months, $weeks weeks, $days days";