PHP Get Two Date Difference Example

Apr 10, 2021 . Admin

Hello Friends,

Now In this blog you'll learn How To Get Two Date Difference in PHP The date_diff() function is an alias of the DateTime::diff. This accepts two DateTime objects as parameters and retruns the difference between them.

Syntax:
date_diff($datetime1, $datetime2[, $absolute])

Parameters

datetime1(Required)
This is a DateTime object, representing one of the dates for the comparison.
$datetime2 (Required)
This is a DateTime object, representing one of the dates for the comparison.
$absolute (Optional)
A boolean value representing whether interval difference should be Must be positive
Return Values

PHP date_diff() function returns a DateInterval object designating the difference between the two given dates. Incase of failure, this function returns erroneous.

Example:

Following example calculates the difference between a given date and the current date −

<?php

   //Creating a DateTime object
   $date1 = date_create("15-08-1997");
   $date2 = date_create();
   $diff = date_diff($date1, $date2);
   print($diff->format('%Y years %m months %d days'));

?>
Output

following output −

23 years 7 months 26 days
Example:

Following example demonstrates the usage of the date_diff() function −

<?php

   $date1 = date_create("15-08-1997");
   $date2 = date_create("10-04-2015");
   $diff = date_diff($date1, $date2);
   print($diff->format('%Y years %m months %d days'));

?>
Output

following output −

17 years 7 months 26 days
Example:

Using user define function calculates the difference between a given date and the current date

<?php

   function date_difference($start_date,$end_date)
      {
        $start = strtotime($start_date);
        $end = strtotime($end_date);

        $diff = $end-$start;
        return round($diff / 86400);
      }  

      echo date_difference("1997-08-15","2021-04-10") . " days" ;

?>
Output

following output −

8639 days

It will help you..

#PHP