English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
PHP Date & Time Function Manual
The date_diff() function returns the difference between two DateTime objects.
The date_diff() function is an alias for DateTime::diff. It accepts two DateTime objects as parameters and calculates the difference between them.
date_diff($datetime1, $datetime2[, $absolute])
Serial number | Parameters and descriptions |
---|---|
1 | datetime1(required) This is a DateTime object representing one of the dates to be compared. |
2 | $datetime2 (required) This is a DateTime object representing one of the dates to be compared. |
3 | $absolute (optional) a boolean value indicating whether the interval difference should be positive |
The PHP date_diff() function returns a DateInterval object specifying the difference between two given dates. If it fails, this function returnsfalse.
This function was initially introduced in PHP version5.3introduced in version 5.2.0 and is available in all higher versions.
The following examples demonstratedate_diff()Function usage-
<?php //Create 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')); ?>Test and see‹/›
Output result
22 years 7 days
The following example calculates the difference between a given date and the current date
<?php $date1 = date_create("25-09-1989"); $date2 = date_create(); $interval = date_diff($date1, $date2; print($interval);-format('%Y year %d day')); ?>Test and see‹/›
Output result
30 year 14 day
Calculate the difference between two dates:
<?php //Create a DateTime object $date1 = date_create("2012-05-09"); $date2 = date_create("2014-01-09"); $interval = date_diff($date1, $date2; print($interval);-format('%Y year %m month %d day')); print("\n"); $date3 = date_create("1989-08-25"); $date4 = date_create("2012-03-19"); $interval = date_diff($date3, $date4; print($interval);-format('%Y year %m month %d day')); print("\n"); $date5 = date_create("2002-11-16"); $date6 = date_create("2014-12-23"); $interval = date_diff($date5, $date6; print($interval);-format('%Y year %m month %d day')); print("\n"); $date7 = date_create("1989-0-09"); $date8 = date_create("2013-05-14"); $interval = date_diff($date7, $date8; print($interval);-format('%Y year %m month %d day')); ?>Test and see‹/›
Output result
01 year 8 month 0 day 22 year 6 month 23 day 12 year 1 month 7 day 24 year 5 month 5 day