How to Get Time Difference Between Two DateTimes in Minutes using PHP

There are two ways to get the time difference in minutes with PHP.

1. Use the PHP DateTime class to calculate the difference between two date-times. The diff() method of DateTime class creates a DateInterval object that calculates the difference between two date/time objects in time (total days, years, months, days, hours, minutes, seconds, etc.).

$datetime_1 '2022-04-10 11:15:30'; 
$datetime_2 '2022-04-12 13:30:45';

$start_datetime = new DateTime($datetime_1);
$diff $start_datetime->diff(new DateTime($datetime_2));

echo 
$diff->days.' Days total<br>';
echo 
$diff->y.' Years<br>';
echo 
$diff->m.' Months<br>';
echo 
$diff->d.' Days<br>';
echo 
$diff->h.' Hours<br>';
echo 
$diff->i.' Minutes<br>';
echo 
$diff->s.' Seconds<br>';

Calculate and get the time difference in minutes:

$total_minutes = ($diff->days 24 60); 
$total_minutes += ($diff->60);
$total_minutes += $diff->i;

echo 
'Diff in Minutes: '.$total_minutes;

2. You can use strtotime() function to get the time difference between two dates (DateTime) in minutes using PHP.

<?php 
$datetime_1 
'2022-04-10 11:15:30';
$datetime_2 '2022-04-12 13:30:45';

$from_time strtotime($datetime_1);
$to_time strtotime($datetime_2);
$diff_minutes round(abs($from_time $to_time) / 60,2). " minutes";

Leave a reply

keyboard_double_arrow_up