What is the best way to calculate the difference between two dates in PHP, especially when retrieving dates from a database?

When calculating the difference between two dates in PHP, especially when retrieving dates from a database, it's best to use the DateTime class. This class provides methods for easy date manipulation and calculation. By creating DateTime objects for the two dates and then using the diff() method, you can easily get the difference in days, months, years, etc.

// Retrieve dates from the database
$date1 = new DateTime($dateFromDatabase1);
$date2 = new DateTime($dateFromDatabase2);

// Calculate the difference between the two dates
$interval = $date1->diff($date2);

// Output the difference in days
echo $interval->days;