0

I trying calculate the difference of days but I need the return of this function in hours.

Well, in my tests follow the code:

<?php

$date1 = new DateTime('2014-05-15 11:00:00');
$date2 = new DateTime('2014-05-14 08:00:00');
$date3 = new DateTime('2014-05-16 10:00:00');
if($date1 != $date2){
    $diff = $date3->diff($date2);

    if($diff->format('%r%h') > 3){
        echo 'error';
        echo '<br />';
        echo $diff->format('%r%h');
    }else{
        echo 'ok';
        echo '<br />';
        echo $diff->format('%r%h');
    }

}else{
    echo 'OK';
}
?>

When I call "echo" with the formated value in this case the value is ever "0". The PHP only calculate the difference in hours. If I need the real return in hour I need calculate the value manual? like:

$days = ($diff->format('%d') * 24 * 60);

Not have the better method to solve this case?

Marcos Bergamo
  • 1,073
  • 2
  • 11
  • 19
  • @AmalMurali Note that the accepted answer in that duplicate is **wrong**. The other answers below are better. – deceze May 16 '14 at 13:16
  • Your misunderstanding: `%h` is only the hour part of, e.g., *"1 week 2 days 3 hours difference"*; it's not the total absolute number of hours. – deceze May 16 '14 at 13:17
  • I stay read the documentation and no have the abolute number of hours. The question suggest of @AmalMurali have an answer. But I don't understant because PHP not calculte automatically this information for us. – Marcos Bergamo May 16 '14 at 13:19
  • @deceze: It isn't completely incorrect. I think this'd be more accurate though: `abs($date1->getTimestamp() - $date2->getTimestamp()) / 60*60`. I couldn't find any better duplicates for this one - if you can find one, please reopen and close as a duplicate of that. – Amal Murali May 16 '14 at 13:20
  • @AmalMurali thanks for your reply, but your code in wrong. `abs($date1->getTimestamp() - $date2->getTimestamp()) /60/60` this return the hours. – Marcos Bergamo May 16 '14 at 13:27
  • @Kefka: Ah, right. `/ 60*60` should have read `/ (60*60)` — see [demo](https://eval.in/152151). – Amal Murali May 16 '14 at 13:31
  • @AmalMurali It's incorrect insofar as it doesn't handle DST correctly, which is an integral part of date/times. Most of the time you won't notice this, but occasionally it will give you an incorrect result, hence it's wrong. Doing the timestamp / 60 / 60 method is indeed correct. – deceze May 16 '14 at 13:33
  • @AmalMurali I do that. Thanks for replies guys! – Marcos Bergamo May 16 '14 at 13:56

0 Answers0