日期差异在php
问题描述:
我有一个函数来计算两个日期之间的差异。日期差异在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.你必须照顾每月的天数。
+0
谢谢! !这是问题.. – era 2012-07-26 10:27: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');
+0
注意:需要PHP 5.3 – zessx 2012-07-26 10:20:42
有很多你选中此http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php – 2012-07-26 10:04:21