[英]How to get a date difference as a negative number in PHP?
I have this code in php to get the difference between two dates.我在 php 中有这段代码来获取两个日期之间的差异。 I'm getting the difference but it's always positive.我得到了差异,但它总是积极的。 I need the difference to be negative when the final date has passed.当最后日期过去时,我需要差异为负。 I've tried format(), invert, but nothing seems to work.我试过 format()、invert,但似乎没有任何效果。
function dias_transcurridos($fecha_i, $fecha_f)
{
$dias = (strtotime($fecha_i) - strtotime($fecha_f)) / 86400;
$dias = abs($dias);
$dias = floor($dias);
return $dias;
}
$hoy = date('Y-m-d');
Then I call the code in my loop:然后我在循环中调用代码:
$elPlazo = dias_transcurridos($row["DateEnd"], $hoy);
echo "<td>" . $elPlazo . " Días</td>\n";
How can I get $elPlazo (the difference) as a negative number when the end date has passed today?今天结束日期过后,如何将 $elPlazo(差额)设为负数?
The problem is that you have an abs
in your code.问题是你的代码中有一个abs
。 abs
will take the absolute value of any number (ie. remove the negative). abs
将取任何数字的绝对值(即删除负数)。 Removing the abs
will make your function return negative differences.删除abs
将使您的函数返回负差异。
I would also think about using the built-in PHP DateTime and DateInterval objects because they can handle things like leap days:我还会考虑使用内置的 PHP DateTime和 DateInterval 对象,因为它们可以处理闰日之类的事情:
<?php
function dias_transcurridos($fecha_i, $fecha_f)
{
$i = new DateTime($fecha_i);
$f = new DateTime($fecha_f);
$interval = $i->diff($f);
return $interval->days;
}
$today = new DateTime(); $今天=新日期时间(); $date = new DateTime('2013-03-10'); $date = new DateTime('2013-03-10');
$interval = $today->diff($date); $interval = $today->diff($date); echo $interval->format("%r%a"); echo $interval->format("%r%a");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.