Calculate the difference between dates in PHP

Right now, will figure out how to compute the distinction between dates in PHP? Utilizing the implicit function of PHP which changes over a date in the string to date design.

Dates are basic information while working in back-end with PHP. Commonly we have to locate the number of years; months and date are between two dates, for example, occasions commencement. Utilizing the implicit function of PHP which changes over a date in the string to date position, we will figure out how to ascertain the contrast between dates in PHP.

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

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

Right now, first, characterize two date variables \$date1 and \$date2 utilizing the standard YYYY-MM-DD configuration and afterwards compute the contrast between them. In any case, we can’t do this straightforwardly as these are in string group.

To change over these dates from string to genuine date-time information type, we utilize the strtotime() function which expects the string that will be changed over into date. Note that the string ought to be a substantial date. The strtotime() converts two dates to Unix time and afterwards ascertain the number of seconds between them. From this present, it’s fairly simple to figure distinctive timeframes. We store the distinction in \$diff variable.

At that point, we compute various pieces of the data utilizing the basic science to change over seconds into years, months and days. We use floor function to get the days, months and days in integer design. For the months, we need to figure from the most recent year. That is the reason we likewise utilized floor in years. Next, we get the date doing incomparable manner, utilizing years and month.

At long last, we print the outcome. On the off chance that you like the article, kindly offer your contemplations in the remarks beneath.

error: Alert: Content is protected!!