-2

I have two different time in a 24-hr format which is time in and timeout. Given the scenario below:

$timeIn = "19:00";
$timeOut = "09:00";
//calculated it using strtotime
$timeDiff = strtotime($timeIn) - strtotime($timeOut);
$timeDiff = ($timeDiff/60)/60;
//result is 10:00

With this one, instead of returning 14hrs, it returns 10hrs only. How can I catch this one out?

UPDATE

Thanks for the comments guys. Here is how I do it:

if($timeIn > $timeOut){
    $timeDiff = 24 - abs(strtotime($timeIn)/60)/60;
    $timeDiff += $timeOut;
}else{
    $timeDiff = strtotime($timeIn) - strtotime($timeOut);
    $timeDiff = ($timeDiff/60)/60;
}
Eem Jee
  • 1,239
  • 5
  • 30
  • 64

4 Answers4

4

Oh.. you could use datetime, as this example:

<?php
$timeIn = new DateTime("2019-09-14 19:00:00");
$timeOut = new DateTime("2019-09-15 09:00:00");

$interval = $timeOut->diff($timeIn);
echo $interval->h;
?>
AnTrakS
  • 733
  • 4
  • 18
  • Thanks fot this one. But my data has no date, so I have tried my approach and works well. – Eem Jee Sep 14 '18 at 09:15
  • 3
    @ramj It *doesn't* work well. And without a date, those times are pretty useless. In timezones which observe DST, you may even get wrong values depending on what day those times actually are. – deceze Sep 14 '18 at 09:16
0

You need to calculate it in timestamp, but to make the complete time you need to use full date format

Example:

$timeIn = "2018-09-14 19:00:00";
$timeOut = "2018-09-15 09:00:00";
//calculated it using strtotime
$timeDiff = strtotime($timeIn) - strtotime($timeOut);

and it gonna work

0

The function returning 10 hours is correct and expectable behaviour.

19-9=10

PHP doesn't know that you want to count the hours from 19:00 to 9:00 the next day. Plase refer to D.Dimitrovs answer which show the correct way using DateTime

Roy Bogado
  • 4,299
  • 1
  • 15
  • 31
dmuensterer
  • 1,875
  • 11
  • 26
  • 2
    I don't understand how an answer stating that another answer is correct (and repeating some comments) could be useful. – Jeff Sep 14 '18 at 09:14
0

For this approach, I have resolved it using this formula and no need to use datetime for I dont have date on my data.

if($timeIn > $timeOut){
    $timeDiff = 24 - abs(strtotime($timeIn)/60)/60;
    $timeDiff += $timeOut;
}else{
    $timeDiff = strtotime($timeIn) - strtotime($timeOut);
    $timeDiff = ($timeDiff/60)/60;
}

Hope this well help the others.

Eem Jee
  • 1,239
  • 5
  • 30
  • 64