Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Get difference between two DateTime objects in Hours, Minutes, and Seconds

Tags:

php

datetime

I'm trying to calculate the number of hours a person has worked on a given day. To do so, I need to get the difference between two DateTime objects in Hours, Minutes, and Seconds. So far I can successfully do so like this

        $timeIn        = new DateTime($time['timeIn']);
        $timeOut       = new DateTime($time['timeOut']);
        $time['hours'] = date_diff($timeIn, $timeOut) -> format("%H:%i:%s");

This seems to work fine, until I put in a test case where the employee forgot to clock out. Now, let's say that

$timeIn  = '2016-09-28 14:26:17'
$timeOut = '2016-09-30 09:53:53'

In that case, the difference SHOULD be 43:27:36 (Because there is over a day in between the timeIn and timeOut). Instead, I get 19:27:36 (as if it's just truncating the days off and returning the rest). How can I add that day onto the hours instead of truncating it? (I'm looking to get 43:27:36, NOT 1day, 19 hours, ect ect. So I'm trying to get the answer in HH:MM:SS)

like image 403
Native Coder Avatar asked Dec 15 '22 03:12

Native Coder


2 Answers

As Scott suggested but with a tweak, we'll need to format this ourselves, but we have nifty sprintf to help:

$start = new \DateTime("2016-09-28 14:26:17");
$end   = new \DateTime("2016-09-30 09:53:53");

$interval = $end->diff($start);

$time = sprintf(
    '%d:%02d:%02d',
    ($interval->d * 24) + $interval->h,
    $interval->i,
    $interval->s
);
like image 199
R. Chappell Avatar answered Dec 16 '22 17:12

R. Chappell


I prefer using the \DateTime objects - although there shouldn't be much of a difference in the end date_diff is just an alias of \DateTime::diff.

You want to check the number of days in the DateInterval object;

$start = new \DateTime("2016-09-28 14:26:17");
$end = new \DateTime("2016-09-30 09:53:53");

$interval = $end->diff($start);

$days = $interval->d;
if ($days > 0) {
    echo $interval->format("%a %h:%i:%s\n");
} else {
    echo $interval->format("%h:%i:%s\n");
}
like image 27
Scott Avatar answered Dec 16 '22 15:12

Scott