• PHP Video Tutorials

PHP date_diff() Function



Definition and Usage

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

Sr.No Parameter & Description
1

datetime1(Mandatory)

This is a DateTime object, representing one of the dates for the comparison.

2

$datetime2 (Mandatory)

This is a DateTime object, representing one of the dates for the comparison.

3

$absolute (Optional)

A boolean value representing whether interval difference should be Must be positive

Return Values

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

PHP Version

This function was first introduced in PHP Version 5.3.0 and, works with all the later versions.

Example

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

Live Demo
<?php
   //Creating a DateTime object
   $date1 = date_create("25-09-1989");
   $date2 = date_create("1-09-2012");
   $interval = date_diff($date1, $date2);
   print($interval->format('%Y years %d days'));
?>

This will produce following result −

22 years 7 days

Example

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

Live Demo
<?php
   $date1 = date_create("25-09-1989");
   $date2 = date_create();
   $interval = date_diff($date1, $date2);
   print($interval->format('%Y years %d days'));  
?>

This will produce following result −

30 years 14 days

Example

<?php
   //Creating a DateTime object
   $date1 = date_create("25-09-2012");
   $date2 = date_create("1-09-2014");
   $interval = date_diff($date1, $date2);
   print($interval->format('%Y years %m months %d days'));
   print("\n");
   $date3 = date_create("25-09-1989");
   $date4 = date_create("19-03-2012");
   $interval = date_diff($date3, $date4);
   print($interval->format('%Y years %m months %d days'));
   print("\n");
   $date5 = date_create("16-11-2002");
   $date6 = date_create("12-09-2014");
   $interval = date_diff($date5, $date6);
   print($interval->format('%Y years %m months %d days'));
   print("\n");
   $date7 = date_create("25-09-1989");
   $date8 = date_create("1-09-2012");
   $interval = date_diff($date7, $date8);
   print($interval->format('%Y years %m months %d days'));
?>

This will produce following result −

01 years 11 months 7 days
22 years 5 months 23 days
11 years 9 months 27 days
22 years 11 months 7 days
php_function_reference.htm
Advertisements