【问题标题】:DateTime class how to deal with negative date intervalDateTime 类如何处理负日期间隔
【发布时间】:2014-02-04 16:29:28
【问题描述】:

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

}

【问题讨论】:

    标签: php datetime dateinterval


    【解决方案1】:

    使用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');
    
    }
    

    【讨论】:

    • 啊,谢谢,那么检查它是否为负数呢?
    • 您可以在执行此操作之前检查$d2 < $d1是否为负数。
    • 啊,我看就这么简单啊
    • 答案通常是。 :)
    • 我们可以使用的其他 '%' 是什么,例如 %a 和 %r :)
    【解决方案2】:

    检查$差异->反转

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

    }

    【讨论】:

      猜你喜欢
      • 2016-05-12
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 2012-09-12
      • 1970-01-01
      相关资源
      最近更新 更多