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


当前回答

function howManyDays($startDate,$endDate) {

    $date1  = strtotime($startDate." 0:00:00");
    $date2  = strtotime($endDate." 23:59:59");
    $res    =  (int)(($date2-$date1)/86400);        

return $res;
} 

其他回答

function howManyDays($startDate,$endDate) {

    $date1  = strtotime($startDate." 0:00:00");
    $date2  = strtotime($endDate." 23:59:59");
    $res    =  (int)(($date2-$date1)/86400);        

return $res;
} 

看看所有的答案,我写了一个通用函数,适用于所有的PHP版本。

if(!function_exists('date_between')) :
    function date_between($date_start, $date_end)
    {
        if(!$date_start || !$date_end) return 0;

        if( class_exists('DateTime') )
        {
            $date_start = new DateTime( $date_start );
            $date_end   = new DateTime( $date_end );
            return $date_end->diff($date_start)->format('%a');
        }
        else
        {           
            return abs( round( ( strtotime($date_start) - strtotime($date_end) ) / 86400 ) );
        }
    }
endif;

一般来说,我使用“DateTime”来查找两个日期之间的天数。但如果出于某种原因,一些服务器设置没有启用'DateTime',它将使用'strtotime()'简单(但不安全)计算。

你可以试试下面的代码:

$dt1 = strtotime("2019-12-12"); //Enter your first date
$dt2 = strtotime("12-12-2020"); //Enter your second date
echo abs(($dt1 - $dt2) / (60 * 60 * 24));

如果你使用的是PHP 5.3 >,这是目前为止最准确的计算绝对差值的方法:

$earlier = new DateTime("2010-07-06");
$later = new DateTime("2010-07-09");

$abs_diff = $later->diff($earlier)->format("%a"); //3

如果你需要一个相对的(带符号的)天数,可以用这个代替:

$earlier = new DateTime("2010-07-06");
$later = new DateTime("2010-07-09");

$pos_diff = $earlier->diff($later)->format("%r%a"); //3
$neg_diff = $later->diff($earlier)->format("%r%a"); //-3

更多关于php的DateInterval格式可以在这里找到:https://www.php.net/manual/en/dateinterval.format.php

    // Change this to the day in the future
$day = 15;

// Change this to the month in the future
$month = 11;

// Change this to the year in the future
$year = 2012;

// $days is the number of days between now and the date in the future
$days = (int)((mktime (0,0,0,$month,$day,$year) - time(void))/86400);

echo "There are $days days until $day/$month/$year";