PASSWORD RESET

Your destination for complete Tech news

PHP

How to calculate the difference between two dates in PHP?

439 0
< 1 min read

To calculate the difference between two dates in PHP, you can use the DateTime class and the diff method.

Here’s an example of how you can use it:

$date1 = new DateTime('2022-12-25');
$date2 = new DateTime('2022-01-01');
$interval = $date1->diff($date2);
echo $interval->format('%R%a days');  // Outputs: +224 days

The diff method returns a DateInterval object, which you can format using the format method. The %R specifier indicates the relative sign of the interval (+ or -), and the %a specifier indicates the number of days in the interval.

You can also use the d specifier to get the number of days as an integer, or the m specifier to get the number of months.

Note that the DateTime class handles time zones and daylight saving time, so you don’t need to worry about those when calculating the difference between two dates.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.