如何使用PHP找到两个日期之间的天数?


当前回答

这段代码为我工作,并用PHP 8版本测试:

function numberOfDays($startDate, $endDate) 
{
    //1) converting dates to timestamps
     $startSeconds = strtotime($startDate);
     $endSeconds = strtotime($endDate);
   
    //2) Calculating the difference in timestamps
    $diffSeconds = $startSeconds  - $endSeconds;
     
    
    //3) converting timestamps to days
    $days=round($diffSeconds / 86400);
    
      /*  note :
          1 day = 24 hours 
          24 * 60 * 60 = 86400 seconds
      */
   
    //4) printing the number of days
    printf("Difference between two dates: ". abs($days) . " Days ");
    
    return abs($days);
}

其他回答

我已经尝试了答案中几乎所有的方法。但是DateTime和date_create在所有测试用例中都没有给出正确答案。特别在2月和3月或12月和1月进行测试。

所以,我想出了混合溶液。

public static function getMonthsDaysDiff($fromDate, $toDate, $includingEnding = false){
    $d1=new DateTime($fromDate);
    $d2=new DateTime($toDate);
    if($includingEnding === true){
        $d2 = $d2->modify('+1 day');
    }
    $diff = $d2->diff($d1);
    $months = (($diff->format('%y') * 12) + $diff->format('%m'));

    $lastSameDate = $d1->modify("+$months month");
    $days = date_diff(
        date_create($d2->format('Y-m-d')),
        date_create($lastSameDate->format('Y-m-d'))
    )->format('%a');

    $return = ['months' => $months,
        'days' => $days];
}

我知道,性能方面这是相当昂贵的。你也可以把它扩展到年限。

从PHP 5.3及以上版本开始,添加了新的日期/时间函数来获得不同:

$datetime1 = new DateTime("2010-06-20");

$datetime2 = new DateTime("2011-06-22");

$difference = $datetime1->diff($datetime2);

echo 'Difference: '.$difference->y.' years, ' 
                   .$difference->m.' months, ' 
                   .$difference->d.' days';

print_r($difference);

结果如下:

Difference: 1 years, 0 months, 2 days

DateInterval Object
(
    [y] => 1
    [m] => 0
    [d] => 2
    [h] => 0
    [i] => 0
    [s] => 0
    [invert] => 0
    [days] => 367
)

希望能有所帮助!

$datediff = floor(strtotime($date1)/(60*60*24)) - floor(strtotime($date2)/(60*60*24));

如果需要的话:

$datediff=abs($datediff);

面向对象的风格:

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');

程序上的风格:

$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');

选择的答案不是最正确的答案,因为它将在UTC之外失败。 根据时区(列表),可能会有时间调整创建“没有”24小时的日子,这将使计算(60*60*24)失败。

这里有一个例子:

date_default_timezone_set('europe/lisbon');
$time1 = strtotime('2016-03-27');
$time2 = strtotime('2016-03-29');
echo floor( ($time2-$time1) /(60*60*24));
 ^-- the output will be **1**

因此,正确的解决方案是使用DateTime

date_default_timezone_set('europe/lisbon');
$date1 = new DateTime("2016-03-27");
$date2 = new DateTime("2016-03-29");

echo $date2->diff($date1)->format("%a");
 ^-- the output will be **2**