开发者

PHP DateDiff issue

Using the PHP code below, I would expect to get '2' as my output. But I get '1'.

Does anyone know why this is?

$returndate = preg_replace('#(\d+)/(\d+)/(\d+)#', '$3-$2-$1', '2011-03-28');
$departdate = preg_replace('#(\d+)/(\d+)/(\d+)#', '$3-$2-$1', '2011-03-26'); 

$diff = abs(strtotime($returndate) - strtotime($departdate));

$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

echo $days; // expecting 2, but get 1
开发者_如何学Go

Many thanks for any help.


So much calculations... I assume its a rounding issue you have, rounding all the time measurements... here is a simpler look on what you are doing:

function dateDiff($start, $end) {
  $start_ts = strtotime($start);
  $end_ts = strtotime($end);
  $diff = $end_ts - $start_ts;
  return round($diff / 86400);
}


$d1 = new DateTime('2011-03-28');
$d2 = new DateTime('2011-03-26');

echo $d1->diff($d2)->d;

Output: 2

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜