-2

I am trying to get the number of minutes between two DateTimes in PHP:

$time = new DateTime($dateString);
$now = new DateTime;
$diff = $time->diff($now);

echo $diff->format('%m');

The result is always 0, although the DateTimes are several hours apart. How would I do this the right way?

John Conde
  • 217,595
  • 99
  • 455
  • 496
Boris
  • 8,551
  • 25
  • 67
  • 120

3 Answers3

7

%m is for months. Minutes is %i:

echo $diff->format('%i');
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • So much for my reading skills... ^^ – Boris Jan 24 '14 at 16:33
  • 1
    You can see all formats in the PHP documentation here: http://fr2.php.net/manual/en/function.date.php – ChoiZ Jan 24 '14 at 16:34
  • One question though: does this return the TOTAL number of minutes? Or the number of minutes MODULO the hours? (if you know what I mean) – Boris Jan 24 '14 at 16:34
  • 1
    It's return the number of minutes MODULO the hours. – ChoiZ Jan 24 '14 at 16:37
  • 1
    It would be modulus hours. So if it is over 59 minutes you would need to factor in hours as well. You could check to see if hours is over zero and, if so, multiply that times 60 to get your total minutes. – John Conde Jan 24 '14 at 16:37
  • 1
    @JohnConde Wouldn't it be a waste of resources to check if hours is over zero, and THEN multiply it? You could just say `hours * 60 + minutes`. – h2ooooooo Jan 24 '14 at 17:10
  • @h2ooooooo Certainly :) – John Conde Jan 24 '14 at 18:16
2

Total number of minutes between 2 datetimes:

$diff = (new DateTime($string))->diff(new DateTime); # PHP >= 5.4.0
#$diff = date_diff(date_create($string), date_create()); # PHP >= 5.3.0
$minutes = ($diff->days * 24 + $diff->h) * 60 + $diff->i;

demo

Glavić
  • 42,781
  • 13
  • 77
  • 107
1

In this case I would keep it simple and use the difference between timestamps/60:-

$minutes = ($date2->getTimestamp() - $date1->getTimestamp())/60;

See it working.

vascowhite
  • 18,120
  • 9
  • 61
  • 77