How to calculate the difference between two dates using PHP?

In this article, we will learn to calculate the difference between dates in PHP? Using the built-in function of PHP which converts a date in string to date format.
Submitted by Abhishek Pathak, on November 01, 2017 [Last updated : March 12, 2023]

PHP - Difference between two dates

Dates are common data while working in back-end with PHP. Many times we need to find the number of years; months and date are between two dates, such as events countdown. Using the built-in function of PHP which converts a date in string to date format, we will learn to calculate the difference between dates in PHP.

PHP code to find the difference between two dates

Following is the code that does it and we will break it in a moment.

<?php
	$date1 = "2007-03-24";
	$date2 = "2009-06-26";

	$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);
?>

Explanation

In this code, we first define two date variables $date1 and $date2 using the standard YYYY-MM-DD format and then calculate the difference between them. But we can't do this directly as these are in string format.

To convert these dates from string to actual date-time data type, we use the strtotime() function which expects the string that will be converted into date. Note that the string should be a valid date. The strtotime() convert two dates to unix time and then calculate the number of seconds between them. From this it's rather easy to calculate different time periods. We store the difference in $diff variable.

Then we calculate different parts of the date using the simple mathematics to convert seconds into years, months and days. We use floor function to get the days, months and days in integer format. For the months, we have to calculate from the last year. That is why we also used floor in years. Next we get the date doing in similar way, using years and month.

Finally, we print the result. If you like the article, please share your thoughts in the comments below.

PHP Basic Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.