PHP | DateTime diff() Function
Last Updated :
10 Oct, 2019
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
$datetime1 = new DateTime( '2019-9-10' );
$datetime2 = new DateTime( '2019-9-15' );
$difference = $datetime1 ->diff( $datetime2 );
echo $difference ->format( '%R%a days' );
?>
|
Program 2:
<?php
$datetime1 = new DateTime( '2019-8-10' );
$datetime2 = new DateTime( '2019-9-10' );
$difference = $datetime1 ->diff( $datetime2 );
echo $difference ->format( '%R%a days' );
?>
|
Reference: https://www.php.net/manual/en/datetime.diff.php
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...