繁体   English   中英

日期在PHP中的天数差异

[英]Date Difference in days in php

我有一个函数来计算两个日期之间的差异。

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;
}

}

对于参数,我首先将这两个日期转换为秒,如下所示,

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

即时差异不到一个月,我得到了正确的差异。 但如果差异超过一个月,我总是得到差异为1.有人可以告诉我,问题是。

目前,一个月总是30 * 60 * 60 * 24秒,又称30天。

你的问题是我们在七月,有31天,而不是30天。你必须照顾每月的天数。

您可以使用DateTime类。 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');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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