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


当前回答

将日期转换为unix时间戳,然后从另一个时间戳中减去一个日期。这将得到以秒为单位的差值,然后除以86400(一天中的秒数),得到该范围内的大约天数。

如果你的日期格式为25.1.2010,01/25/2010或2010-01-25,你可以使用strtotime函数:

$start = strtotime('2010-01-25');
$end = strtotime('2010-02-20');

$days_between = ceil(abs($end - $start) / 86400);

使用ceil将天数四舍五入到下一个全天。如果您希望获得这两个日期之间的完整天数,则使用floor。

如果日期已经是unix时间戳格式,则可以跳过转换,只执行$days_between部分。对于更奇特的日期格式,您可能必须进行一些自定义解析以使其正确。

其他回答

将日期转换为unix时间戳,然后从另一个时间戳中减去一个日期。这将得到以秒为单位的差值,然后除以86400(一天中的秒数),得到该范围内的大约天数。

如果你的日期格式为25.1.2010,01/25/2010或2010-01-25,你可以使用strtotime函数:

$start = strtotime('2010-01-25');
$end = strtotime('2010-02-20');

$days_between = ceil(abs($end - $start) / 86400);

使用ceil将天数四舍五入到下一个全天。如果您希望获得这两个日期之间的完整天数,则使用floor。

如果日期已经是unix时间戳格式,则可以跳过转换,只执行$days_between部分。对于更奇特的日期格式,您可能必须进行一些自定义解析以使其正确。

$now = time(); // or your date as well
$your_date = strtotime("2010-01-31");
$datediff = $now - $your_date;

echo round($datediff / (60 * 60 * 24));

你可以试试下面的代码:

$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
function dateDiff($firstDate,$secondDate){
    $firstDate = strtotime($firstDate);
    $secondDate = strtotime($secondDate);

    $datediff = $firstDate - $secondDate;
    $output = round($datediff / (60 * 60 * 24));
    return $output;
}
?>

像这样调用这个函数

<?php
    echo dateDiff("2018-01-01","2018-12-31");    

// OR

    $firstDate = "2018-01-01";
    $secondDate = "2018-01-01";
    echo dateDiff($firstDate,$secondDate);    
?>

看看所有的答案,我写了一个通用函数,适用于所有的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()'简单(但不安全)计算。