How to Use the PHP date_diff() Function

09/09/2021

Contents

In this article, you will learn how to use the PHP date_diff() function.

PHP date_diff() Function

The date_diff() function in PHP is used to calculate the difference between two dates. It returns a DateInterval object that represents the difference between two dates.

Syntax:
date_diff(DateTime $datetime1, DateTime $datetime2) : DateInterval
Example:
<?php
  $datetime1 = new DateTime('2022-01-01');
  $datetime2 = new DateTime('2022-06-30');
  $interval = date_diff($datetime1, $datetime2);
  echo $interval->format('%R%a days');
?>
Output:
+181 days

In this example, we create two DateTime objects, $datetime1 and $datetime2, and pass them as arguments to the date_diff() function. The date_diff() function returns a DateInterval object, which we then format using the format() method to display the difference in days.

The date_diff() function calculates the difference between two dates and returns a DateInterval object that represents that difference. The DateInterval object has several properties and methods that you can use to access and format the difference.

Here are some of the properties of the DateInterval object:

  • y: The number of years between the two dates.
  • m: The number of months between the two dates.
  • d: The number of days between the two dates.
  • h: The number of hours between the two dates.
  • i: The number of minutes between the two dates.
  • s: The number of seconds between the two dates.

Here is the methods of the DateInterval object:

  • format(string $format): This method is used to format the difference into a human-readable string. The $format argument is a string that specifies the format of the output. For example, %y represents the number of years, %m represents the number of months, and %d represents the number of days.

Here’s an example that shows how to use some of the properties and methods of the DateInterval object:

<?php
  $datetime1 = new DateTime('2022-01-01');
  $datetime2 = new DateTime('2022-06-30');
  $interval = date_diff($datetime1, $datetime2);

  echo "Difference: " . $interval->format('%y years, %m months, %d days');
  echo "<br>";
  echo "Years: " . $interval->y;
  echo "<br>";
  echo "Months: " . $interval->m;
  echo "<br>";
  echo "Days: " . $interval->d;

  //Output
  //Difference: 0 years, 5 months, 29 days
  //Years: 0
  //Months: 5
  //Days: 29
?>

In this example, we calculate the difference between two dates and then use the format() method to format the difference into a human-readable string. We also access the y, m, and d properties to get the number of years, months, and days between the two dates.