我有两个时间戳让我们说
$end_date = 2014-09-09 15:03:10 and now date
date_default_timezone_set('Asia/Calcutta');
$now = date('Y-m-d H:i:s');
我想计算剩余的天数。假设特定日期现在越过现在的日期,它应该显示剩余天数-ve值。
我正在使用以下代码
$remaining_days =strtotime($end_date) - strtotime($now) ;
$Result_days = floor($remaining_days /86400);
echo $remaining_days.' '.$Result_days.'<br/>'
问题是,如果结束日期=今天的日期,则显示-1。我想根据时间计算并显示剩余的天数和小时数。 请帮我找出解决方案。
答案 0 :(得分:1)
试试这个:
<?php
$end_date = "2014-10-09 15:03:10";
date_default_timezone_set('Asia/Calcutta');
$now = date('Y-m-d H:i:s');
$diff = strtotime($now) - strtotime($end_date);
$fullDays = floor($diff/(60*60*24));
$fullHours = floor(($diff-($fullDays*60*60*24))/(60*60));
$fullMinutes = floor(($diff-($fullDays*60*60*24)-($fullHours*60*60))/60);
echo "Difference is $fullDays days, $fullHours hours and $fullMinutes minutes.";
的输出:强>
差异是-30天,0小时39分钟。
的演示:强>
编辑(使用日期对象):
<?php
// Example 1
$end_date = "2014-09-11 20:35:10";
date_default_timezone_set('Asia/Calcutta');
$now = date('Y-m-d H:i:s');
$date1=date_create($now);
$date2=date_create($end_date);
$diff=date_diff($date1,$date2,FALSE);
echo $diff->format("%R%d days, %h hours, %m minutes, %s seconds").PHP_EOL;
//Output:
+2 days, 3 hours, 0 minutes, 44 seconds
// Example 2
$end_date = "2014-09-08 20:35:10";
date_default_timezone_set('Asia/Calcutta');
$now = date('Y-m-d H:i:s');
$date1=date_create($now);
$date2=date_create($end_date);
$diff=date_diff($date1,$date2,FALSE);
echo $diff->format("%R%d days, %h hours, %m minutes, %s seconds").PHP_EOL;
//Output:
-0 days, 20 hours, 0 minutes, 16 seconds
的演示:强>
答案 1 :(得分:1)
您可以使用date_diff
php方法。您可以在此处查看示例http://php.net/manual/en/function.date-diff.php
答案 2 :(得分:0)
您可以尝试这样:
<?php
$dateDiff = $date1 - $date2;
$fullDays = floor($dateDiff/(60*60*24));
$fullHours = floor(($dateDiff-($fullDays*60*60*24))/(60*60));
$fullMinutes = floor(($dateDiff-($fullDays*60*60*24)-($fullHours*60*60))/60);
echo "Differernce is $fullDays days, $fullHours hours and $fullMinutes minutes.";
?>
有关更多选项,请参阅Source
$date1 = new DateTime("2014-09-09");
$date2 = new DateTime("2014-09-12");
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";