[英]How to get the date difference in minus value in PHP
I'm trying to get the date difference in minus value if the start_Date is greater than the end_date.如果 start_Date 大于 end_date,我试图获得负值的日期差异。 below is my code下面是我的代码
$diff = strtotime('2019-07-31') - strtotime('2019-07-21');
$date_diff = round($diff / 86400);
the code gives me 10
as answer, but i want -10
.代码给了我10
作为答案,但我想要-10
。 how should i get it?我应该如何得到它?
All you need to use %r
format.所有你需要使用%r
格式。 This format prints a minus (-) sign if the difference is negative, or nothing otherwise.如果差异为负,则此格式会打印减号 (-),否则不会打印任何内容。
<?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
Here it is.这里是。 just put a negative sign before rounding.在四舍五入前加一个负号。
$diff = strtotime('2019-07-31') - strtotime('2019-07-21');
$date_diff = - round($diff / 86400); // here is the change you need
echo $date_diff;
Output:输出:
-10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.