Jesse Elser
Jesse Elser

Reputation: 976

PHP Date Calculator Returning Wrong Days

I'm using the below calculator to determine the years, months, and days between a set date and the current date. I thought it was working fine, but then it came up on the year mark and i noticed it was not working properly. Tomorrow is actually when the one year mark would be, but it is currently returning 11 months, 34 days. Could anyone tell me whats wrong? It should be 11 months, 30 days.

function relationshipTimer($functionDate)
{
    $date1 = $functionDate;
    $date2 = date("Y-m-d");
    $diff = abs(strtotime($date2) - strtotime($date1));
    $years = floor($diff / (365 * 60 * 60 * 24));
    $months = floor(($diff - ($years * 365 * 60 * 60 * 24)) / ((365 * 60 * 60 * 24) / 12));
    $days = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24) / (60 * 60 * 24));
    if ($years > 0) {echo $years . " Year";}
    if ($years > 1) {echo "s ";}
    if ($months > 0) {echo " " . $months . " Month";}
    if ($months > 1) {echo "s ";}
    if ($date1 == $date2) {echo "1 Day ";}
    if ($days > 0) {echo $days . " Day";}
    if ($days > 1) {echo "s ";}
}

And this is where $functionDate comes from:

relationshipTimer("2018-04-28");

Upvotes: 2

Views: 65

Answers (1)

xhienne
xhienne

Reputation: 6144

When you calculate $days, you are assuming that all months are 30 days long, which is obviously wrong. Therefore you get a year that is 11 months plus 35 days (36 days for leap years).

Processing dates is complicated. You should always use specialized tools like PHP's DateTime::diff()

For example, with:

$date1 = new DateTime("2018-04-28");
$date2 = new DateTime("2019-04-27");
$diff = $date2->diff($date1);
print $diff->format("%y years %m months %d days\n");

... you get (because April has 30 days):

0 years 11 months 29 days

Upvotes: 5

Related Questions