PHP | DateTime diff() Function
The DateTime::diff() function is an inbuilt function in PHP which is used to return the difference between two given DateTime objects.
Syntax:
- Object oriented style:
DateInterval DateTime::diff( DateTimeInterface $datetime2, bool $absolute = FALSE )or
DateInterval DateTimeImmutable::diff( DateTimeInterface $datetime2, bool $absolute = FALSE )or
DateInterval DateTimeInterface::diff( DateTimeInterface $datetime2, bool $absolute = FALSE ) - Procedural style:
DateInterval date_diff( DateTimeInterface $datetime1, DateTimeInterface $datetime2, bool $absolute = FALSE )
Parameters: This function uses two parameters as mentioned above and described below:
- $datetime: This parameter holds the date to compare with first date.
- $absolute: This parameter forced the interval to be positive.
Return Value: This function return the difference between two given DateTime objects.
Below programs illustrate the DateTime::diff() function in PHP:
Program 1:
<?php // Initialising the two datetime objects $datetime1 = new DateTime('2019-9-10'); $datetime2 = new DateTime('2019-9-15'); // Calling the diff() function on above // two DateTime objects $difference = $datetime1->diff($datetime2); // Getting the difference between two // given DateTime objects echo $difference->format('%R%a days'); ?> |
+5 days
Program 2:
<?php // Initialising the two datetime objects $datetime1 = new DateTime('2019-8-10'); $datetime2 = new DateTime('2019-9-10'); // Calling the diff() function on above // two DateTime objects $difference = $datetime1->diff($datetime2); // Getting the difference between two // given DateTime objects echo $difference->format('%R%a days'); ?> |
+31 days
Reference: https://www.php.net/manual/en/datetime.diff.php
Recommended Posts:
- PHP | Ds\Set diff() Function
- PHP | Ds\Map diff() Function
- PHP | DateTime add() Function
- PHP | DateTime sub() Function
- How to convert JavaScript datetime to MySQL datetime ?
- PHP | DateTime setDate() Function
- PHP | DateTime createFromFormat() Function
- PHP | DateTime modify() Function
- PHP | DateTime format() Function
- HTML | <del> datetime Attribute
- HTML | <ins> datetime Attribute
- HTML | DOM ins dateTime Property
- HTML | datetime Attribute
- HTML | DOM del dateTime Property
- HTML | DOM Input Datetime min Property
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



