user4803090
user4803090

Reputation: 59

Difference between 2 datetimes in minutes?

I got the following code:

$now = new DateTime();
$then = new DateTime($accountExists['sub_limit']);

$interval = $then->diff($now);
$hours   = $interval->format('%h'); 
$minutes = $interval->format('%i');
echo  'Diff. in minutes is: '.($hours * 60 + $minutes);

which returns the difference between 2 datetimes in minutes. If then is 2015-05-31 19:15:31 and now is 2015-05-31 19:20:31 it returns 5 minutes. But as soon as the day changes, if then changes to 2015-05-30 19:15:31 it still returns 5 minutes when it should be 1445 minutes. Could someone point out my error?

Upvotes: 0

Views: 148

Answers (2)

JayTaph
JayTaph

Reputation: 2916

Because months, years can have an arbitrary number of minutes, you might best want to convert your dates to timestamps (seconds since epoch) so you only have to divide by 60. Fortunately, it's easy to do so:

$now = new DateTime('2015-05-31 19:20:31');
$then = new DateTime('2015-05-30 19:15:31');

$seconds = abs($now->format('U') - $then->format('U'));
$minutes = floor($seconds / 60);

print $minutes;

Upvotes: 4

Rizier123
Rizier123

Reputation: 59681

That is because it's a full day. So you have to calculate how many minutes one day is. So this should work for you:

Basically here I just get all days, hours, minutes and seconds from the interval and multiply them by the multiplier to get minutes out of them.

<?php

    //Test data
    $now = "2015-05-30 19:20:31";
    $accountExists['sub_limit'] = "2015-05-30 19:15:31";

    $now = new DateTime($now);
    $then = new DateTime($accountExists['sub_limit']);

    $interval = $then->diff($now);
    $multiplier = ["days" => 60*24, "h" => 60, "i" => 1, "s" => 1/60];
    $minutes = 0;
    $values = array_intersect_key((array)$interval, $multiplier);
    foreach($values as $k => $v)
        $minutes += $v*$multiplier[$k];

    echo  "Diff. in minutes is: " . $minutes;

?>

output:

Diff. in minutes is: 1445

Upvotes: 0

Related Questions