Question

So my query is like this:

SELECT TIMEDIFF('24:00:00',(TIMEDIFF('22:00:00',TIME(end)))) AS time
FROM sworkingtime
WHERE user='magdalena' AND type='work' AND start BETWEEN '2014-03-01' AND '2014-03-28' AND (HOUR(`end`) > 22 OR HOUR(`end`) < 4)
AND completed=1

My query returns this:

02:02:36
03:17:24
03:07:03
02:24:17
03:14:09

Is there a way to modify this query to return only SUM of this fields, so one field only?

Thank you

Was it helpful?

Solution

No, there's no special sum function in this case - especially paying attention that you need some time summation, not just simple operation.

To do that, you can apply callback on your array. Very powerful function for that is array_reduce(). For working with date intervals you can use DateTime API, like:

$data = [
  ['time'=>'02:02:36'],
  ['time'=>'03:17:24'],
  ['time'=>'03:07:03']
];


$time = array_reduce($data, function($c, $x)
{
   $x = explode(':', $x['time']);
   $c = explode(':', $c);
   return (new DateTime('2000-01-01'))
      ->add(new DateInterval('PT'.(int)$c[0].'H'.(int)$c[1].'M'.(int)$c[2].'S'))
      ->add(new DateInterval('PT'.(int)$x[0].'H'.(int)$x[1].'M'.(int)$x[2].'S'))
      ->format('H:i:s');
}, '00:00:00');

-this will result in "08:27:03" as string. But if you want to get object, remove format() call.

OTHER TIPS

You can iterate the array and use this function to sum Sum time php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top