How to subtract dates in laravel?

10

I need to calculate working time on a call. For this I need to do operations with date , how do I do this in laravel ?

Code:

 public function ticketsByUserSearch(Request $request)
{
    $user = new User();
    $user = $user->find($request->user_id);
    if (!$request->initial_date) {
        $data = Ticket::where('user_id', '=', $request->user_id)->get();
    } else {
        $initial = $request->initial_date;
        $final = $request->final_date;
        $data = Ticket::where('user_id', '=', $request->user_id)
            ->where('created_at', '>=', $initial)
            ->where('created_at', '<=', $final)
            ->get();

        $jobTime = 0;
        foreach ($data as $ticket){
            $jobTime = $jobTime + ($ticket->closing_date - $ticket->created_at); //preciso de ajuda aqui
        }

        dd($jobTime);
    }
    $pdf = \PDF::loadView('reports.tickets-by-user-pdf', ['data' => $data, 'user' => $user]);
    return $pdf->stream();
}
    
asked by anonymous 08.09.2016 / 15:48

1 answer

16

There is a package installed on Laravel , Carbon > which makes several operations with date. Since you did not say which operation you really want to do, I put the difference between days of two dates as an example, and it's a simple process with this package.

Difference in days:

$date1 = Carbon::createFromFormat('Y-m-d', '1999-01-01');
$date2 = Carbon::createFromFormat('Y-m-d', '2000-01-01');

$value = $date2->diffInDays($date1); // saída: 365 dias

Difference in hours:

$date1 = Carbon::createFromFormat('Y-m-d H:i:s', '1999-01-01 15:00:00');
$date2 = Carbon::createFromFormat('Y-m-d H:i:s', '1999-01-01 17:00:00');

$value = $date2->diffInHours($date1); // saída: 2 horas

In Api doc you even have an interesting example between dates and times in countries of locations with different time zones

$dtToronto = Carbon::createFromDate(2012, 1, 1, 'America/Toronto');
$dtVancouver = Carbon::createFromDate(2012, 1, 1, 'America/Vancouver');

echo $dtVancouver->diffInHours($dtToronto); // 3

Reference site:

08.09.2016 / 16:12