繁体   English   中英

如何在PHP中获得负值的日期差异

[英]How to get the date difference in minus value in PHP

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

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

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

所有你需要使用%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

这里是。 在四舍五入前加一个负号。

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

echo $date_diff;

输出:

-10 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM