Calculating Date Differences in PHP
Given two dates in the format "2007-03-24" and "2009-06-26," you seek a PHP solution to determine the difference between them in the form "2 years, 3 months, and 2 days."
Solution
Leveraging DateTime and DateInterval objects, the following PHP code accomplishes your goal:
$date1 = new DateTime("2007-03-24"); $date2 = new DateTime("2009-06-26"); $interval = $date1->diff($date2); echo "difference " . $interval->y . " years, " . $interval->m . " months, " . $interval->d . " days";
For a total day count without partitioning into years, months, and days, use:
echo "difference " . $interval->days . " days";
Additional Notes
$date1 = new DateTime("now"); $date2 = new DateTime("tomorrow"); var_dump($date1 == $date2); // false var_dump($date1 < $date2); // true var_dump($date1 > $date2); // false
The above is the detailed content of How Can I Calculate the Difference Between Two Dates in PHP and Display the Result as Years, Months, and Days?. For more information, please follow other related articles on the PHP Chinese website!