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.
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);
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With