Search code examples
phplaravelphp-carbon

I want to `start_time` and `end_time` count how can get this?


How can count between start_time and end_time time

$time_all = Carbon::now()->toArray();

if ($input['type'] == 'start') {
                  /*  $data = [
                        'start_time' => $time, 'contract_id' => $input['job_id'],'engineer_id' => $userid, 'type' => 'start'
                    ];*/

$start_time = JobTimingLog::create([
                        'start_time' => $time, 'contract_id' => $input['job_id'],'engineer_id' => $userid, 'type' => 'start'
                    ])->id;
$arr = array("status" => 200, "message" => "start_time Add Successfully", "data" => array('start_time' => $time, 'id' => $start_time));
} else if ($input['type'] == 'end') {
$data_end = DB::table('job_timing_logs')->where('contract_id', $input['job_id'])->where('id', $input['id'])->update(['end_time' => $time, 'type' => 'end']);
$arr = array("status" => 200, "message" => "end_time update Successfully", "data" => $times);
}

Now I want to count between start_time and end_time


Solution

  • Since you didn't specify where did you get the $time variable content and in what format is it, I'll assume $time is start datetime and $end_time is end datetime and you want to take the time difference between those two. It can be done using Carbon difference package like this:

    // Assume $time = '2019-12-06 00:00:00' and $end_time = '2019-12-06 18:00:00'
    $start_time = Carbon::parse($time); // Parse the datetime to Carbon object first
    $end_time = Carbon::parse($end_time);
    $diff_in_hours = $start_time->diffInHours($end_time);
    $diff_in_minutes = $start_time->diffInMinutes($end_time);
    $diff_in_seconds = $start_time->diffInSeconds($end_time);