What are some best practices for formatting and displaying date differences in PHP output?

When displaying date differences in PHP output, it is important to format the output in a user-friendly way that is easy to understand. One common approach is to calculate the time difference between two dates and display it in a human-readable format such as "X days ago" or "X hours ago". This can be achieved using PHP's built-in date and time functions.

// Calculate the time difference between two dates
$date1 = new DateTime('2022-01-01');
$date2 = new DateTime('2022-01-10');
$interval = $date1->diff($date2);

// Display the time difference in a user-friendly format
if ($interval->d > 0) {
    echo $interval->format('%a days ago');
} elseif ($interval->h > 0) {
    echo $interval->format('%h hours ago');
} else {
    echo 'Less than an hour ago';
}