era
era

Reputation: 535

Date Difference in days in php

I have a function to calculate the difference between two dates.

function getDateDifference($to, $from, $in) {
$diff = abs($to - $from);

$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));
if ($in == "days") {
    return $days;
} else if ($in == "months") {
    return $months;
} else if ($in == "years") {
    return $years;
}

}

For the parameters i first convert the two dates into seconds like this,

checkin = '2012-07-26';
checkout = '2012-07-27';
check_in_date = strtotime(checkin);
check_out_date = strtotime(checkout);

im getting the correct difference when it comes to difference less than one month. But if the difference is more than one month, im always getting the difference as 1. Can someone tell me wat the problem is.

Upvotes: 1

Views: 633

Answers (2)

Falco van Dooremolen
Falco van Dooremolen

Reputation: 33

You can make use of the DateTime class. http://php.net/manual/en/datetime.diff.php

 $checkin = new DateTime("2012-07-23");
 $checkout = new DateTime("2012-07-27");
 $difference = $checkin->diff($checkout);
 echo "differrence = " . $difference->format('%R%a days');

Upvotes: 1

zessx
zessx

Reputation: 68790

Currently, a month is always 30 * 60 * 60 * 24 sec, aka 30 days.

Your problem is that we're in July, and there are 31 days, not 30. You must take care of number of days per month.

Upvotes: 2

Related Questions