Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding days between two dates in laravel

Tags:

laravel-5

I have to dates. Now, I need to find the difference between these two for further calculations.

I tried different ways but I am not able to fix the issues. Can anyone tell me the best way to do it.

My code is:

public function leaveRequest(request $request)
{
    $fdate=$request->Fdate;
    $tdate=$request->Tdate;

    $start = Carbon::parse($fdate)->format('Y/m/d');
    $end =  Carbon::parse($tdate)->format('Y/m/d');

    $days = $end->diffInDays($start);
    /*$days=date_diff($end,$start);*/
    echo $days;
    exit;

    $user = User::findOrFail(Auth::user()->id);
    Mail::send('pages.leave', ['user' => $request,'userId'=>$user], function ($m) use ($request) {
        $m->to($request->Email)->subject('Leave Request!');
    });

    DB::table('leaves')->insert(
        ['user' => Auth::user()->id, 'request_date' => Carbon::now(),'start' => $start,'end' => $end,'permissions' => "Pending",'leave_status' => "Active"]
    );

    return redirect()->back()->with('message','Your request has sent');
}

If I can get the days then I can insert it into the leaves table.

like image 969
Kiran Rai Chamling Avatar asked Jan 03 '17 12:01

Kiran Rai Chamling


People also ask

How to find number of days between two dates in Laravel?

function dateDiffInDays($date1, $date2) { $diff = strtotime($date2) - strtotime($date1); return abs(round($diff / 86400)); } // Start date $date1 = "2021-03-01 04:03:00"; // End date $date2 = date('Y-m-d'); $dateDiff = dateDiffInDays($date1, $date2);

How can I get days between two dates in PHP?

The date_diff() function is an inbuilt function in PHP that is used to calculate the difference between two dates. This function returns a DateInterval object on the success and returns FALSE on failure.


1 Answers

You don't need Carbon, you can do that using simple PHP. Best is to use PHP OOP way. Like this:

$fdate = $request->Fdate;
$tdate = $request->Tdate;
$datetime1 = new DateTime($fdate);
$datetime2 = new DateTime($tdate);
$interval = $datetime1->diff($datetime2);
$days = $interval->format('%a');//now do whatever you like with $days

PS : DateTime is not a function, its a class so don't forget to add : use DateTime; at top of your controller so that it can reference to right root class or use \DateTime() instead when making its instance.

I hope it helps

like image 133
Abhay Maurya Avatar answered Oct 01 '22 01:10

Abhay Maurya