Home » PHP

Calculate difference between dates in 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

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.

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

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.







Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.