find days between two dates

Welcome back to shortlearner.com, in this post we will see how to get days between two dates by using
pre-defined PHP function.
PHP provide us a diff() function , that are helpful to find days between two dates.
in below example we will get days using Object oriented style and Procedural style as well.count days between two dates using php

Also Read :

facebook like chat system using php , mysql and ajax

make a dynamic pi chart using php and mysql

Read excel file using JavaScript html

Object oriented style

<?php
$datetime1 = new DateTime('2019-03-01');
$datetime2 = new DateTime('2019-03-10');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>
Output : 9

Procedural style

<?php
$datetime1 = date_create('2019-03-01');
$datetime2 = date_create('2019-03-10');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
?>
output : 9

Days Difference Between two dates in PHP

<?php
$daysLeft = 0;
$fromDate = "2019-02-25";
$curDate = date('Y-m-d');
$daysLeft = abs(strtotime($curDate) - strtotime($fromDate));
$days = $daysLeft/(60 * 60 * 24);

printf("Days difference between %s and %s = %d", $fromDate, $curDate, $days);
 ?>
output : Days difference between 2019-02-25 and 2019-03-01 =4

here we subtract current date to previous data by using abs() php method for absolute value, and we also using strtotime() function that will help us to convert date into unix time-stamp and getting difference between two dates in a timestamp, finally we converting this timestamp into days using formula (second in a minute * minutes in an hour * hour in a day).

PHP Difference in Months Between two Dates

<?php
$fromDate = new DateTime('2016-03-15');
$curDate = new DateTime();

$months = $curDate->diff($fromDate);
echo $months->format('%m months');
 ?>
output : 8 months

Note: All the above function are useful for PHP Version:5.3+