Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP program to find the total number of date between any two given dates
The date_diff() function can be used to get the difference between two dates. It is a built-in function that returns a DateInterval object containing the difference between the dates.
Syntax
date_diff(datetime1, datetime2, absolute)
Parameters
datetime1 − The first date object
datetime2 − The second date object
absolute (optional) − If set to TRUE, the interval will always be positive
Example
The following example demonstrates how to find the total number of days between two given dates ?
<?php
$date_1 = date_create('23-11-2019');
$date_2 = date_create('22-1-2020');
$day_diff = date_diff($date_1, $date_2);
echo $day_diff->format('The day difference is: %R%a days');
?>
The day difference is: +60 days
Using DateTime Objects
You can also use DateTime objects directly for calculating date differences ?
<?php
$start_date = new DateTime('2023-01-01');
$end_date = new DateTime('2023-12-31');
$interval = $start_date->diff($end_date);
echo 'Total days: ' . $interval->days;
?>
Total days: 364
Getting Absolute Difference
To always get a positive result regardless of date order, use the absolute parameter ?
<?php
$date1 = new DateTime('2024-01-01');
$date2 = new DateTime('2023-01-01');
$diff = date_diff($date1, $date2, true);
echo 'Absolute difference: ' . $diff->days . ' days';
?>
Absolute difference: 365 days
Conclusion
The date_diff() function provides an easy way to calculate the difference between two dates in PHP. Use the %a format specifier to get the total number of days, and set the absolute parameter to true for always positive results.
