There are three times obtained from the DB (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); 

Considers not quite right. For example:

Turn on time: 04:47:00

Off 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?

  • Breaks - is the sum of all the breaks?) You need to translate them into seconds and just take away not as strtotime but just as seconds from the total time value - Moonvvell
  • It turned out to be a little easier, put the installation of the time zone GMT-10, removed, now instead of 20:38:27 writes 05:38:27 - g431k
  • You understand that a correctly calculated difference should be on the side of time zones? After all, it is an hour in Africa. - vp_arth

1 answer 1

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 formatted time, it is easier to store it simply as the number of seconds.
  2. There are no dates where they are needed. It is necessary to manually check the fact of changing dates. If someone wants to work more than a day, the result will be incorrect.
  • If done in this way, it gives an error: "Parse error: syntax error, unexpected '['" - g431k
  • The first row is just initialization, you must have another source for $row . - vp_arth
  • Thanks for the clarification, my mistake, I understood everything. Now swears at "Unknown or bad format (PTS) '" - g431k
  • What do you have in $row['4'] ? Apparently empty. There must be some number of seconds - vp_arth
  • The request selects all records for a specific employee. $ row ['4'] - total number of breaks, that is, they may not exist at all. With zero time it does not turn out that way, I guess so? - g431k