What is the purpose of the PHP date_diff function?

The date_diff() function in PHP is used to calculate the difference between two date and time values. It returns a DateInterval object that contains information about the difference between the two date and time values, such as years, months, days, hours, minutes, and seconds.

Here is the basic syntax of the date_diff() function.

date_diff(DateTimeInterface $datetime1, DateTimeInterface $datetime2): DateInterval

$datetime1 and $datetime2 are the two date-time objects to be compared.

Here is a simple example demonstrating how to use the date_diff() function to calculate the difference between two date times.

$date1 = new DateTime('2022-01-01');
$date2 = new DateTime('2022-02-15');

$interval = date_diff($date1, $date2);

echo $interval->format('%R%a days'); // 输出:+45 days

In this example, we first create two date-time objects $date1 and $date2, then calculate the difference between them using the date_diff() function and store the result in the $interval variable. Finally, we use the format() method to format the difference information, so that the output is in the form of days.

bannerAds