Get difference between date returns zero

I have a date time in 'Ymd H:i:s', and i tried to substract the now date with the defined date +1 day to get remaining time in hours, minutes and seconds:

$time = '2017-10-05 14:54:03';
$now =  date('Y-m-d H:i:s');
$endTransaction = date('Y-m-d H:i:s', strtotime($time. ' + 1 day'));
$dteDiff  = $endTransaction - $now;
echo $dteDiff;

but i always get 0 as the result


You are doing it wrong. The date function returns string so PHP is not able to compare anything. Try with the DateTime class instead. Its diff method returns the DateInterval object with some public properties, like the days property among others, which is the positive integer number (rounded down) of days between two dates:

$now = new DateTime();
$endTransaction = (new DateTime('2017-12-05 14:54:03'))->modify('+1 day');

$diff = $endTransaction->diff($now);

printf(
    'Difference in days: %d, hours: %d, minutes: %d, seconds: %d',
     $diff->days,
     $diff->h,
     $diff->m,
     $diff->s
);

你可能需要使用这个date_diff

    $time = '2017-10-05 14:54:03';
    $now =  date_create(date('Y-m-d H:i:s'));
    $endTransaction = date_create(date('Y-m-d H:i:s', strtotime($time. ' + 1 day')));
    $dteDiff  = date_diff($now, $endTransaction);
    $date = new DateTime($dteDiff);

    $result = $date->format('Y-m-d H:i:s');

根据上述描述,请尝试执行以下代码片段作为解决方案。

    $time = '2017-10-05 14:54:03';
    $now =  strtotime(date('Y-m-d H:i:s'));
    $endTransaction = strtotime(date('Y-m-d H:i:s', strtotime($time. ' + 1 day')));
    $dteDiff  = ($endTransaction - $now)/(24*60*60);
    echo round($dteDiff);
链接地址: http://www.djcxy.com/p/10122.html

上一篇: 为什么setTimeout(fn,0)有时有用?

下一篇: 获取日期之间的差异返回零