Home > Backend Development > PHP Tutorial > How Can I Calculate the Difference Between Two Dates in PHP and Display the Result as Years, Months, and Days?

How Can I Calculate the Difference Between Two Dates in PHP and Display the Result as Years, Months, and Days?

Barbara Streisand
Release: 2025-01-04 03:20:38
Original
354 people have browsed it

How Can I Calculate the Difference Between Two Dates in PHP and Display the Result as Years, Months, and Days?

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";
Copy after login

For a total day count without partitioning into years, months, and days, use:

echo "difference " . $interval->days . " days";
Copy after login

Additional Notes

  • PHP allows comparison of DateTime objects using "==", "<", and ">".
  • The following example demonstrates date comparison:
$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");

var_dump($date1 == $date2); // false
var_dump($date1 < $date2); // true
var_dump($date1 > $date2); // false
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template