php计算日期之间

时间:2013-09-12 10:34:58

标签: php date

我有以下代码,2个日期之间的2个计算天数:

 $start = '2013-04-02'; 
 $end = '';
 if($end){ 
 $now = $end; 
 }else{
 $now = time();
 }
 $your_date = strtotime($start);
 $datediff = $now - $your_date;
 echo floor($datediff/(60*60*24));

这样可以正常工作并计算正确的天数。

当我输入这样的结束日期时:

 $start = '2013-04-02'; 
 $end = '2013-09-11';
 if($end){ 
 $now = $end; 
 }else{
 $now = time();
 }
 $your_date = strtotime($start);
 $datediff = $now - $your_date;
 echo floor($datediff/(60*60*24));

我得到-15797的结果。

以上看似乎没问题?或者我做错了什么?

2 个答案:

答案 0 :(得分:1)

试试这个::

$start    = new DateTime('2013-04-02');
$end      = new DateTime('2013-09-11');
$interval = DateInterval::createFromDateString('1 day');
$period   = new DatePeriod($start, $interval, $end);
$count=count($period);
echo $count; 

答案 1 :(得分:0)

应该是:

 $start = '2013-04-02'; 
 $end = '2013-09-11';
 if($end){ 
 $now = strtotime($end); 
 }else{
 $now = time();
 }
 $your_date = strtotime($start);
 $datediff = $now - $your_date;
 echo floor($datediff/(60*60*24));