0

我有一个简单的函数,它使用 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;

}
4

2 回答 2

4

使用r标志在其中获取负号:

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');

}
于 2014-02-04T16:32:06.667 回答
2

检查 $difference->invert

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

}

于 2014-02-04T17:16:24.477 回答