Search code examples
laraveldatetimelaravel-bladelaravelcollective

How to use Collective and Blade to get the time difference in Laravel


I wish to calculate $time_used with using Collective and Blade in Laravel.

All date format of time_start, time_stop and time_used is timestamp in DB.

I tried to calculate with using Carbon, but I couldn't got time_used.

Also "time_start" from "created_at" and "time_stop" from "deleted_at" in DB.

Could you tell me how to get the time difference. Thanks.

in \show_fields.blade.php

    <!-- Time Start Field -->
    <div class="form-group">
        {!! Form::label('time_start', 'Time Started:') !!}
        <p>{!! $job->created_at !!}</p>
    </div>

    <!-- Time Stop Field -->
    <div class="form-group">
        {!! Form::label('time_stop', 'Time Stopped:') !!}
          <p>{!! $job->deleted_at !!}</p>            
    </div>

    <!-- Time Used Field -->
    <div class="form-group">
        {!! Form::label('time_used', 'Time Used:') !!}
        <p>{!! $job->time_used !!}</p>
    </div>

Result was as below...

Job Started:
2017-09-17 17:51:39

Job Stopped:
2017-09-17 17:51:49

Time Used:

Solution

  • You can get the difference in seconds between the two timestamps and then format it to H:i:s

    gmdate("H:i:s",Carbon::parse($job->deleted_at)->diffInSeconds(Carbon::parse($job->created_at)));

    Or

    Carbon::parse($job->deleted_at)->diff(Carbon::parse($job->created_at))->format('%H:%I:%S');

    Which should return something like 00:00:10 in the format Hours:Minutes:Seconds