1

I need to calculate the total hours worked by guards. I am able to get each shifts' total hours, but I don't know how to add them together. I have a users table, a signIn table and a Shift table. Here is what I got so far.

In the Controller:

$signIns = $em->getRepository('AppBundle:SignIn')
        ->findAllThisMonthDesc();

    foreach ($signIns as $signIn) {
        $diff[$signIn->getId()]['signInId'] = $signIn->getId();
        $diff[$signIn->getId()]['shiftId'] = $signIn->getShift();
        $diff[$signIn->getId()]['workerId'] = $signIn->getWorker();
        $diff[$signIn->getId()]['hoursWorked'] = date_diff($signIn->getSignedInAt(), $signIn->getSignedOutAt() );
    }


    return$this->render('users/show.html.twig', [
        'user' => $user,
        'memos' => $memos,
        'loggedInUser' => $loggedInUser,
        'phoneScreenings' => $phoneScreenings,
        'sites' => $sites,
        'signIns' => $signIns,
        'diff' => $diff,
    ]);

The Twig Template:

{% for signIn in signIns %}
     {% for dif in diff %}
          {% if signIn.worker.id == user.id and signIn.shift.id == dif.shiftId.id and dif.workerId.id == user.id  %}
               {{ dif.hoursWorked.h }}hrs, {{ dif.hoursWorked.i }} mins -
          {% endif %}
     {% endfor %}
{% endfor %}

My output is something like 9hrs and 2 mins - 12hrs and 43 mins. But I want it to be added together so that it displays 21 hrs, 44 mins

Chris
  • 57,622
  • 19
  • 111
  • 137
  • 1
    Why don't you do your calculation in the Controller and then send the value to Twig instead? Although in Twig, you could simply create a Variable and then add the 9hrs, 2min and 12hrs, 43mins to the variable. But this may be somehow complex because what if you have 9hrs, 45 and 12hrs, 50mins? You would have to do some conversion of (43mins +50mins) into hours again, which, though achievable, could be quite a work. – Poiz May 26 '16 at 07:00

2 Answers2

4

Why don't you do your calculation in the Controller and then send the value to Twig instead? Although in Twig, you could simply create a Variable and then add the 9hrs, 2min and 12hrs, 43mins to the variable. But this may be somehow complex because what if you have 9hrs, 45 and 12hrs, 50mins? You would have to do some conversion of (43mins +50mins) into hours again, which, though achievable, could be quite a work.

    <?php           

        $signIns = $em->getRepository('AppBundle:SignIn')
                      ->findAllThisMonthDesc();

        foreach ($signIns as $signIn) {
            $diff[$signIn->getId()]['signInId']    = $signIn->getId();
            $diff[$signIn->getId()]['shiftId']     = $signIn->getShift();
            $diff[$signIn->getId()]['workerId']    = $signIn->getWorker();
            $diff[$signIn->getId()]['hoursWorked'] = date_diff($signIn->getSignedInAt(), $signIn->getSignedOutAt() );
        }



        $hours      = 0;
        $minutes    = 0;
        $extraHours = 0;
        foreach ($signIns as $signIn) {
            foreach($diff as $dif){
                if($signIn['workerId'] == $user['id'] && $signIn['shiftId'] == $dif['shiftId'] && $dif['workerId'] == $user['id'] ){
                    $hours      += $dif['hoursWorked']['h'];
                    $minutes    += $dif['hoursWorked']['i'];
                }
            }
        }

        if($minutes >= 60){
            $extraHours = intval( $minutes/60 );
            $minutes    =  $minutes%60;
        }

        $realTotal      = ($hours + $extraHours) . "hrs, " . $minutes . "mins";


        return$this->render('users/show.html.twig', [
            'user'              => $user,
            'memos'             => $memos,
            'loggedInUser'      => $loggedInUser,
            'phoneScreenings'   => $phoneScreenings,
            'sites'             => $sites,
            'signIns'           => $signIns,
            'diff'              => $diff,
            'realTotal'         => $realTotal,
        ]);


        // IN TWIG YOU CAN DO JUST...
        {{ realTotal }}
Poiz
  • 7,611
  • 2
  • 15
  • 17
  • thank you so much for your help, however I get a error message Error: Cannot use object of type AppBundle\Entity\SignIn as array, the error stems from this line in the controller: if($signIn['workerId'] == $user['id'] && $signIn['shiftId'] == $dif['shiftId'] && $dif['workerId'] == $user['id'] ){ – Kosta Andonovski May 31 '16 at 06:15
  • I had to change the syntax for calling the object like so: $signIn->getWorker() == $user->getId(), however now I am getting another error: Notice: Object of class Proxies\__CG__\AppBundle\Entity\User could not be converted to int – Kosta Andonovski May 31 '16 at 06:24
  • I am also getting an error for the hours and minutes addition directly below with the following error message: Error: Cannot use object of type DateInterval as array from this line: $hours += $dif['hoursWorked']['h']; – Kosta Andonovski May 31 '16 at 06:38
  • 1
    @Kosta Andonovski The reason you are getting Errors should be from **your implementation of findAllThisMonthDesc() in your Repository Class**. That method does not return an Array.... it returns an Object: **AppBundle\Entity\SignIn** instead. Since it is a Repository. You can possibly change the return value to be an **Array of AppBundle\Entity\SignIn**. That could do the trick for you... – Poiz May 31 '16 at 10:51
0

You must calculate it in your controller :

$totalHours = new \DateTime('00:00:00');

foreach ($signIns as $signIn) {
            foreach($diff as $dif){
                if($signIn['workderId'] == $user['id'] && $signIn['shiftId'] == $dif['shiftId'] && $dif['workerId'] == $user['id'] ){
                   $totalHours = self::addtime($totalHours, $dif['hoursWorked']);
                }
            }
        }

And use this function :

public function addtime($time1,$time2)
{
    $interval1 = $time1->diff(new \DateTime('00:00:00')) ;
    $interval2 = $time2->diff(new \DateTime('00:00:00')) ;

    $e = new \DateTime('00:00');
    $f = clone $e;
    $e->add($interval1);
    $e->add($interval2);
    $total = $f->diff($e)->format("%H:%I:%S");
    return new \DateTime($total);
}

Source : Adding two DateTime objects in php

Community
  • 1
  • 1
Kvn91
  • 176
  • 1
  • 10