If you were given two dates, that is start date and end date and You want to find the difference between two dates in PHP.
Its very simple and easy to calculate the difference between two dates.
There are two methods to find the difference.
Contents
By using date_diff() in-built function to Calculate Difference Between Two Dates in PHP
For php version >=5.3 : Create two date objects and then use date_diff() function. It will return php DateInterval object.
$date1 = date_create("2018-03-24");
echo "Start date: ".$date1->format("Y-m-d")."<br>";
$date2 = date_create("2019-05-31");
echo "End date: ".$date2->format("Y-m-d")."<br>";
$diff = date_diff($date1,$date2);
echo "Difference between start date and end date: ".$diff->format("%y years, %m months and %d days");
Output by using date_diff() function
If you execute the above code to find the difference between start date and end date, you will get the below output
Start date: 2018-03-24
End date: 2019-05-31
Difference between start date and end date: 1 years, 2 months and 7 days
By using strtotime() function in PHP
You can use strtotime() to convert two dates to unix time and then calculate the number of seconds between them. From this it’s rather easy to calculate difference between start date and end date.
$date1 = "2018-03-24";
$date2 = "2019-05-31";
$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
printf("%d years, %d months, %d days\n", $years, $months, $days);
Output by using strtotime() function
If you execute the above code to find the difference between start date and end date using strtotime() function, you will get the below output
1 years, 2 months, 8 days
That’s it. I hope you will like this tutorial. Please share this post with your friends in your social media by clicking share options. Please share your feedback via comments
Thanks