0

I'm trying to calculate the difference of two times. I'm using this method to return the difference in minutes.

$datetime1 = new DateTime('9.00am');
$datetime2 = new DateTime('10.15am');
$interval = $datetime1->diff($datetime2);
$timeDuration = $interval->format('%im');

However, the $timeDuration returns 15m instead of 75m. Any help that could correct the code to let it return the exact correct difference in minutes ?

hatched
  • 795
  • 2
  • 9
  • 34
  • Have you checked whether the inputed dates were parsed properly? – Nico Haase Feb 01 '19 at 08:52
  • 1
    Possible duplicate of [How to get time difference in minutes in PHP](https://stackoverflow.com/questions/365191/how-to-get-time-difference-in-minutes-in-php) – Nico Haase Feb 01 '19 at 08:54

3 Answers3

1

Because the difference between 9am and 10:15am is 1 hour ($interval->h) and 15 minutes ($interval->i), not 75 minutes literally.

If you wish to get the total number of minutes, you have to calculate it:

$differenceInMinutes = $interval->i + ($interval->h * 60);

If you wish to have more universal solution, I would go for the unix time:

$differenceInSeconds = abs($datetime1->format('U') - $datetime2->format('U'));

$differenceInMinutes = ceil($differenceInSeconds / 60);
Mike Doe
  • 16,349
  • 11
  • 65
  • 88
0

The simple way to get different in minutes

<?php

 $start = date_create('1990-01-01 09:00:00');
 $end = date_create('1990-01-01 10:15:00');

 $interval=date_diff($end, $start);

 $hours   = $interval->format('%h'); 
 $minutes = $interval->format('%i');

 $in_minutes = $hours * 60 + $minutes;

 echo  'Diff. in minutes is: '.$in_minutes;

?>
Googlian
  • 6,077
  • 3
  • 38
  • 44
0

When you are trying to calculate the difference between two DateTime's like $datetime1 = new DateTime('9.00am'); and $datetime2 = new DateTime('10.15am'); you know that the difference is 75 minutes, but the resulto of diff() method is 1 hour for $interval->h and 15 minutes for $interval->i. So this is how you can calculate it:

$datetime1 = new DateTime('9.00am');
$datetime2 = new DateTime('10.15am');
$interval = $datetime1->diff($datetime2);
$hours   = $interval->format('%h'); 
$minutes = $interval->format('%i');
$difference_in_minutes = $hours * 60 + $minutes;

echo  'Difference in minutes is: ' . $difference_in_minutes . "\n";

There a working snipped in this link

Teocci
  • 7,189
  • 1
  • 50
  • 48