Subtracting time

There are three times obtained from the database (Arrival time, Departure time, and breaks). I try to do this:

    $time1 = strtotime($row['3']); // Время выключения
    $time2 = strtotime($row['2']); //Время включения
    $time3 = strtotime($row['4']); //Перерывы
    $diff = $time1-$time2-$time3;
    $summi = floor($diff);

It doesn't count quite right. Eg:

Turn-on time: 04: 47: 00

Shutdown time: 05: 33: 00

Breaks: 00: 07: 33

It should turn out 00: 38:27 and it turns out 20: 38: 27

What's wrong?

Author: g431k, 2017-02-06

1 answers

You can use DateInterval to correctly calculate the difference.
If I understand correctly, $row[4] contains the total number of seconds for breaks.

$row = [
  '2' => '2017-02-06 08:00:00',
  '3' => '2017-02-06 18:10:00',
  '4' => 3660
];

$dateOn  = new \DateTime($row['2']);
$dateOff = new \DateTime($row['3']);
$delays = (int)$row['4'];
$dateOn->add(new DateInterval('PT'.$delays.'S'));

$time = $dateOff->diff($dateOn);
echo $time->format('%H:%I:%S'); // 09:09:00

$row = [
  '2' => '06:25:00',
  '3' => '07:00:00',
  '4' => '00:10:00'
];

$dateOn  = new \DateTime($row['2']);
$dateOff = new \DateTime($row['3']);

if ($dateOn > $dateOff) {
  $dateOff->add(DateInterval::createFromDateString('1 day'));
}    

if ($row['4']) {
  list($h, $i, $s) = explode(':', $row[4]);
  $dateOn->add(new DateInterval("PT{$h}H{$i}M{$s}S"));
}
$time = $dateOff->diff($dateOn);
echo $time->format('%H:%I:%S'); // 00:25:00

This format is very unfortunate:

  1. The interval is stored as a formatted time, it is easier to store it simply as the number of seconds.
  2. There are no dates where they are needed. You have to manually check the fact of changing the dates. If someone wants to work for more than a day, the result will be incorrect.
 2
Author: vp_arth, 2017-02-06 10:49:24