-1

I'm currently working with a timekeeping system which computes the sum of the basic hours of the week and deduct certain time if there's a late record.

Given that the employee has a total hours rendered for this week is 45 hours (45:00), and he she/has a total late record for that week of 50 minutes (00:50),

Using, PHP. How can I deduct the late record to the total hours rendered without converting time to decimal? The desired output for the above sample is 44:10 since 00:50 is deducted to 45:00.

  • 1
    Possible duplicate of [How to get time difference in minutes in PHP](https://stackoverflow.com/questions/365191/how-to-get-time-difference-in-minutes-in-php) – Obsidian Age Nov 09 '17 at 03:11

2 Answers2

0

You can convert the string to a date and get the difference.

$d1 = "00:45:00";
$d2 = "00:00:50";

date_default_timezone_set("utc");

$fakedate = '01/01/2017';

$d1 = $fakedate . ' ' . $d1;
$d2 = $fakedate . ' ' . $d2;

$dt1 = new DateTime($d1);
$dt2 = new DateTime($d2);


$diff = $dt1->diff($dt2);

echo $diff->format("%H:%I:%S");

The output will be: 00:44:10

SteveB
  • 894
  • 7
  • 15
  • Hi, thanks for the comment. But whenever I'm exceeding the hours count to 60, I receiving a fatal error, maybe because we used minutes in this case. – user3819290 Nov 09 '17 at 06:41
  • If you want to exceed an hour count of 60, you would need to change $fakedate to be two different dates. It would work unto 23 hours and 59 minutes at which point the date needs to change based on how many days it is. I would adjust my answer, but it seems you have a good answer above. – SteveB Nov 09 '17 at 15:14
0

I see so your goal is to subtract durations ex.

45:00 - 00:50 = 44:10

1: Create a function that convert them into hours

function convertToHours($duration) {
   $duration = explode(':',$duration);
   $hours+= (int)$duration[0];
   $hours+= (int)$duration[1] / 60;
   return $hours;
}

2: Create a funciton thats convert from seconds to duration hours:seconds

    function secondsToDuration($seconds) {
      $H = floor($seconds / 3600);
      $i = ($seconds / 60) % 60;
      $s = $seconds % 60;
      return sprintf("%02d:%02d:%02d", $H, $i, $s);
    }
  1. Convert them into hours using function created

    $duration1 = convertToHours("25:00");
    $duration2 = convertToHours("00:50");
    
  2. Then subtract them

    $difference = $duration1 - $duration2;
    
  3. Lastly use the created method which convert them back into duration

    $duration = secondsToDuration($difference * 3600);
    

See Demo here

Hope it helps you

Beginner
  • 4,118
  • 3
  • 17
  • 26