如何在PHP中计算两个日期时间之间的分钟差异?


当前回答

求两个日期之差的方法在这里。有了这个功能,你可以找到秒、分、小时、天、年和月等差异。

function alihan_diff_dates($date = null, $diff = "minutes") {
 $start_date = new DateTime($date);
 $since_start = $start_date->diff(new DateTime( date('Y-m-d H:i:s') )); // date now
 print_r($since_start);
 switch ($diff) {
    case 'seconds':
        return $since_start->s;
        break;
    case 'minutes':
        return $since_start->i;
        break;
    case 'hours':
        return $since_start->h;
        break;
    case 'days':
        return $since_start->d;
        break;      
    default:
        # code...
        break;
 }
}

你可以开发这个函数。我测试过了,结果对我有用。DateInterval对象输出如下:

/*
DateInterval Object ( [y] => 0 [m] => 0 [d] => 0 [h] => 0 [i] => 5 [s] => 13 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 0 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 ) 
*/

功能用途:

$date =过去的日期, $diff =类型eg:“分钟”,“天”,“秒”

$diff_mins = alihan_diff_dates("2019-03-24 13:24:19", "minutes");

祝你好运。

其他回答

另一种以分钟为单位计算差异的简单方法。请注意,这是一个在1年范围内计算的样本。详情请点击这里

$origin = new DateTime('2021-02-10 09:46:32');
$target = new DateTime('2021-02-11 09:46:32');
$interval = $origin->diff($target);
echo (($interval->format('%d')*24) + $interval->format('%h'))*60; //1440 (difference in minutes)
$date1=date_create("2020-03-15");
$date2=date_create("2020-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");

有关详细的格式说明,请访问链接。

这是一个简单的一行代码:

$start = new DateTime('yesterday');
$end = new DateTime('now');
$diffInMinutes = iterator_count(new \DatePeriod($start, new \DateInterval('PT1M'), $end));

我想这对你有帮助

function calculate_time_span($date){
    $seconds  = strtotime(date('Y-m-d H:i:s')) - strtotime($date);

        $months = floor($seconds / (3600*24*30));
        $day = floor($seconds / (3600*24));
        $hours = floor($seconds / 3600);
        $mins = floor(($seconds - ($hours*3600)) / 60);
        $secs = floor($seconds % 60);

        if($seconds < 60)
            $time = $secs." seconds ago";
        else if($seconds < 60*60 )
            $time = $mins." min ago";
        else if($seconds < 24*60*60)
            $time = $hours." hours ago";
        else if($seconds < 24*60*60)
            $time = $day." day ago";
        else
            $time = $months." month ago";

        return $time;
}

DateTime::diff很酷,但对于这种需要单个单元结果的计算来说很尴尬。手动减去时间戳效果更好:

$date1 = new DateTime('2020-09-01 01:00:00');
$date2 = new DateTime('2021-09-01 14:00:00');
$diff_mins = abs($date1->getTimestamp() - $date2->getTimestamp()) / 60;