简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM