Calculate the difference between two dates in PHP
In this PHP tutorial, we are going to calculate the date difference between two dates. At first, we will take two dates and by using PHP we will find how many days difference between these two dates.
Before we are going to see our code example, let’s get some information about the PHP date_diff() function. The date_diff() is an inbuilt function in PHP which is used to find the difference between two days.
Below is the syntax for PHP date_diff function:
In above syntax, the start_date and the end_date parameter are mandatory which are specifies the DateTime objects. The absolute parameter is optional. Here we can set boolean value. By default it is false. The true value of absolute always returns the date difference in positive.
Now see the example below where we are getting the difference between two dates:
<?php $start_date=date_create("2018-05-18"); $end_date=date_create("2018-03-16"); $date_diff=date_diff($start_date,$end_date); echo $date_diff->format("%R%a days"); ?>
The above code will show the difference between two dates in days. Here in the example, we will see the negative sign. If we want to make it always positive then we have to add boolean true to the date_diff() PHP function just like below:
Also if we want to see the difference with the current date, we can create our date by leaving the parameter to the date_create() function empty just like below:
So we have just seen how to get the date difference between any two dates in PHP.