Kalidass
Kalidass

Reputation: 434

Date and time difference display 30min as 5

I have tried to compare two dates and time using this php code

<?php $A = "2013-01-10 10:30:00";
    $B = "2013-01-10 12:00:00";
    echo str_replace('-','',(strtotime($A) - strtotime($B))/(60*60));
    ?>

code working fine but its display 30 min as 5 so i not able to checks this with db values any idea to fix this one

Upvotes: 2

Views: 65

Answers (2)

Sougata Bose
Sougata Bose

Reputation: 31739

strtotime() alone can calculate the difference. There is no need to use str_replace(). Try with -

echo (strtotime($B) - strtotime($A))/60;

Will return the difference in minutes ie. 90. If you want it like 1.30 then have to do some basic calculations. -

$mins = (strtotime($B) - strtotime($A))/60;
if ($mins > 60) {
    echo ((int)($mins/60)).'.'.($mins%60);
} else {
    echo $mins;
}

Upvotes: 2

Pedro Lobito
Pedro Lobito

Reputation: 98901

I've updated my answer based on your comment, to get the difference in hours (ie: 1.5) you need:

 $A = "2013-01-10 10:30:00";
 $B = "2013-01-10 12:00:00";

echo (strtotime($B) - strtotime($A))/3600;

Output:

1.5

demo: http://ideone.com/ovEr0F

Upvotes: 1

Related Questions