To calculate the difference in days between two DateTime
objects in PHP, you can use the diff()
method of the DateTime
class, which returns a DateInterval
object. Here's an example:
$datetime1 = new DateTime('2020-01-01');
$datetime2 = new DateTime('2020-02-15');
$interval = $datetime1->diff($datetime2);
$days = $interval->days;
echo "Difference in days: " . $days;
In the above example, we create two DateTime
objects $datetime1
and $datetime2
representing January 1, 2020, and February 15, 2020, respectively.
Next, we use the diff()
method to calculate the difference between the two dates. This returns a DateInterval
object $interval
.
Finally, we retrieve the number of days from $interval
using the days
property and display it using echo
.
The output will be:
Difference in days: 45