【问题标题】:Date Difference in days in phpphp中的日期差异
【发布时间】:2012-07-26 09:59:16
【问题描述】:

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

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。有人可以告诉我问题是什么。

【问题讨论】:

标签: php mysql


【解决方案1】:

目前,一个月总是30 * 60 * 60 * 24 秒,也就是 30 天。

您的问题是我们在七月,有 31 天,而不是 30 天。您必须注意每个月的天数。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 2010-12-20
      • 2010-12-28
      • 2010-11-26
      • 2012-02-17
      相关资源
      最近更新 更多