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


当前回答

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

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

其他回答

$date1=date_create("2020-03-15");
$date2=date_create("2020-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");

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

我想这对你有帮助

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;

时区的另一种方法。

$start_date = new DateTime("2013-12-24 06:00:00",new DateTimeZone('Pacific/Nauru'));
$end_date = new DateTime("2013-12-24 06:45:00", new DateTimeZone('Pacific/Nauru'));
$interval = $start_date->diff($end_date);
$hours   = $interval->format('%h'); 
$minutes = $interval->format('%i');
echo  'Diff. in minutes is: '.($hours * 60 + $minutes);

试试这个

$now = \Carbon\Carbon::now()->toDateString(); // get current time 
             $a = strtotime("2012-09-21 12:12:22"); 
             $b = strtotime($now);
             $minutes = ceil(($a - $b) / 3600); it will get ceiling value