How to subtract dates in the Laravel?

Asked

Viewed 4,872 times

10

I need to calculate the working time on a call. For this I need to do operations with date, how do I do this in the 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();
}
  • What Date Operation You Need to Do ?

  • I need the time difference.

  • I edited the answer, and put two examples !!!

1 answer

17


There is a package installed on Laravel, the Carbon that does several operations with date. As I did not say which operation I really want to do, I put as an example the difference between days of two dates, being 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 doc Api there is even an interesting example between dates and times in countries 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

Website reference:

  • 2

    It worked, thank you very much.

  • It is worth remembering that the Carbon extends the Datetime, a native PHP object that is responsible for doing all this ai =) including in the examples shown only the diffInHours is exclusive to Carbon.

  • @gmsantos, all right, I hope so. Good on the methods that calculate differences, really the DateTime does this only that in Carbon is ready and with implementations that help a lot in the development Laravel which is what is on the tag. If you want to give an example with Datetime it is comfortable when more answers better, thank you.

  • 1

    It was just an observation to complement the answer (which is already well completed by the way) :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.