What Is the PHP DateDiff Function?
PHP version 5.3 includes a DateTime class for storing, manipulating and performing calculations with dates and a DateInterval class for storing the interval between two dates. The DateTime class includes several methods, such as the DateTime::diff method, which returns the difference between two DateTime objects as a DateInterval object. The date_diff function is a procedural style alias of the DateTime::diff method that can be used to calculate the difference between two dates.
-
DateTime Class
-
The DateTime class in PHP is a construct that represents a date and time. It includes several methods that allow you to manipulate dates and perform date calculations. The DateTime class stores a date internally as the number of seconds since the Unix Epoch, which is Jan. 1, 1970, at 00:00:00 GMT. Create a new DateTime object with "new" and the DateTime construct or procedurally with the date_create function. For example:
<?php
$party = new DateTime('1999-12-31');
$same_party = date_create("1999-12-31");
?>
DateTime::diff
-
The DateTime::diff method allows you to calculate the difference between two DateTime objects. For example, to calculate the number of days you have been alive, write a function to calculate the difference between today's date and your birth date:
<?php
function daysAlive($birthdate) {
$today = new DateTime("now");
$birthday = new DateTime($birthdate);
$daysAlive = $birthday->diff($today);
return $daysAlive->format("%a days');
}
?>
-
date_diff Function
-
The date_diff function is a procedural-style alias of the DateTime::diff method. Use the date_create function to create a DateTime object and use the date_diff function to calculate the interval between two dates. For example, the procedural-style function that calculates the number of days you have been alive is:
<?php
function days_alive($birth_date) {
$today = date_create("now");
$birthday = date_create($birth_date);
$days_alive = date_diff($birthday, $today);
return date_interval_format($days_alive, "%a days");
}
?>
DateInterval Class
-
When you use the DateTime::diff method or the date_diff function, the result is represented as an object of the DateInterval class. This class stores the interval between two dates as a fixed period of time in years, months, days, hours and seconds. The object-oriented DateInterval::format method or the procedural-style date_interval_format function allow you to display the date interval in one or more time periods. For example, you could display a date interval as a number of days or as a number of years and days:
<?php
$first_date = date_create("2011-09-05");
$second_date = date_create("2020-06-01");
$diff = date_diff($second_date, $first_date);
echo date_interval_format($diff, "%a days");
echo date_interval_format($diff, "%y years and %d days");
?>
-