DateTime类如何处理负日期间隔

时间:2014-02-04 16:29:29

标签: php datetime dateinterval

我有一个简单的函数,它使用DateTime diff函数返回两个日期之间的天数。但是现在如果结束日期早于开始日期,它仍会返回正数。有没有办法使用这种方法返回负面差异?或者我会打赌更好,只是先在我的功能中检查strtotime?理想情况下,我认为我只会返回0的负面差异。

//Returns the total number of days between two dates
function count_days($start_date, $end_date){

    $d1 = new DateTime($start_date);
    $d2 = new DateTime($end_date);
    $difference = $d1->diff($d2);
    return $difference->days;

}

2 个答案:

答案 0 :(得分:4)

使用r flag获取负号:

function count_days($start_date, $end_date){

    $d1 = new DateTime($start_date);
    $d2 = new DateTime($end_date);
    $difference = $d1->diff($d2);
    return $difference->format('%r%a days');

}

答案 1 :(得分:2)

检查$ difference->反转

function count_days($start_date, $end_date){

   $d1 = new DateTime($start_date);
   $d2 = new DateTime($end_date);
   $difference = $d1->diff($d2);
   if ($difference->invert == 1) { //if 1 then difference will in minus other wise inplus
      return -$difference->d;
   } else {
     return $difference->d;
   }

}