簡體   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