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.
Advertisement
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
1 2 3 4 5 6 | <?php $datetime1 = new DateTime('2019-03-01'); $datetime2 = new DateTime('2019-03-10'); $interval = $datetime1->diff($datetime2); echo $interval->format('%R%a days'); ?> |
1 | Output : 9 |
Procedural style
1 2 3 4 5 6 | <?php $datetime1 = date_create('2019-03-01'); $datetime2 = date_create('2019-03-10'); $interval = date_diff($datetime1, $datetime2); echo $interval->format('%R%a days'); ?> |
1 | output : 9 |
Days Difference Between two dates in PHP
1 2 3 4 5 6 7 8 9 | <?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); ?> |
1 | output : Days difference between 2019-02-25 and 2019-03-01 =4 |
PHP Difference in Months Between two Dates
1 2 3 4 5 6 7 | <?php $fromDate = new DateTime('2016-03-15'); $curDate = new DateTime(); $months = $curDate->diff($fromDate); echo $months->format('%m months'); ?> |
1 | output : 8 months |
Note: All the above function are useful for PHP Version:5.3+