0

I'm tracking the amount of total time each employee has spent at work from the moment of employment.

I have the entries table (Check in/Check Out), and the time gets calculated after the checkout happens.

However, I have the relevant column for that in integer format, and if FOR EXAMPLE someone enters at 10:53:07 and leaves at 11:18:31, it displays 24 as a result (since there's 24 seconds between 07 and 31). Basically resets back to 0 once it reaches 60.

Picture:

Example

Here's the relevant code I use in the controller for summation:

    $employees = Employee::all();


    $totals = [];

    foreach($employees as $employee)
    {
        $totals[$employee->id] = $employee->attendances->sum('time_spent_working');
    }

I formatted time_spent_working as an integer in the migration itself. What would be the best/cleanest solution here?

Stephan Vierkant
  • 9,674
  • 8
  • 61
  • 97
GiorgiMG
  • 1
  • 2
  • Possible duplicate of [Output is in seconds. convert to hh:mm:ss format in php](https://stackoverflow.com/questions/3534533/output-is-in-seconds-convert-to-hhmmss-format-in-php) – Royal Wares Feb 07 '19 at 08:04

3 Answers3

0

I would calculate this difference when needed using the Carbon diffForHumans functionality instead of saving this in the database.

Like so

$startDate = Carbon::parse($date->entered);
$endDate = Carbon::parse($date->left);

$diff = $startDate->diffInDays($endDate);

If you want an absolute number, instead of a human-readable one, you could use Carbons diffInSeconds which gives the amount of seconds, even when it is more then 60. But then you'd have to have some logic to display seconds/minutes/hours etc.

Sitethief
  • 480
  • 5
  • 17
0

use diff function

$startTime = "2019-01-05 23:20:25";
 $start  = new Carbon($startTime);
  $finishTime = "2019-01-06 01:20:30";
  $end    = new Carbon($finishTime);
$end->diff($start)->format('%H:%I:%S');
Palak Jadav
  • 1,202
  • 1
  • 11
  • 23
0

I managed to do it via the gmdate function (Inserted this into the view)

<td>{{ gmdate("H:i:s", $totals[$employee->id]) }}</td>

If it helps, I've been storing the diff in time in SECODNS

From the controller:

$attendance->time_spent_working = $attendance->checked_out_at->diffInSeconds($attendance->checked_in_at);
GiorgiMG
  • 1
  • 2