【问题标题】:How to get the date difference in minus value in PHP如何在PHP中获取负值的日期差异
【发布时间】:2020-01-20 05:11:59
【问题描述】:

如果 start_Date 大于 end_date,我会尝试获取负值的日期差异。下面是我的代码

    $diff =  strtotime('2019-07-31') - strtotime('2019-07-21');
    $date_diff = round($diff / 86400);

代码给了我10 作为答案,但我想要-10。我应该如何获得它?

【问题讨论】:

  • $diff = strtotime('2019-07-21') - strtotime('2019-07-31');?
  • @Nick 你想问什么?
  • 只用相反的方式编写代码 (end-start) 而不是 (start-end)

标签: php date difference


【解决方案1】:

所有你需要使用%r 格式。如果差值为负,则此格式打印减号 (-),否则不打印。

<?php

function dateDifference($date_1 , $date_2 , $differenceFormat = '%r%a' ) {
    $datetime1 = date_create($date_1);
    $datetime2 = date_create($date_2);

    $interval = date_diff($datetime1, $datetime2);

    return $interval->format($differenceFormat);

}

echo dateDifference('2019-07-31', '2019-07-21'); // -10

【讨论】:

    【解决方案2】:

    来了。只需在四舍五入前加上一个负号。

    $diff =  strtotime('2019-07-31') - strtotime('2019-07-21');
    $date_diff =  - round($diff / 86400); // here is the change you need
    
    echo $date_diff;
    
    

    输出:

    -10 
    

    【讨论】:

      猜你喜欢
      • 2023-01-15
      • 1970-01-01
      • 1970-01-01
      • 2020-01-28
      • 2017-11-28
      • 2020-09-29
      • 1970-01-01
      • 2014-01-05
      • 1970-01-01
      相关资源
      最近更新 更多