Finding days between two dates in laravel

牧云@^-^@ 提交于 2021-01-21 03:53:25

问题


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.


回答1:


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




回答2:


$to = \Carbon\Carbon::createFromFormat('Y-m-d H:s:i', '2015-5-5 3:30:34');
$from = \Carbon\Carbon::createFromFormat('Y-m-d H:s:i', '2015-5-6 9:30:34');

$diff_in_days = $to->diffInDays($from);

print_r($diff_in_days); // Output: 1



回答3:


Anyone using PHP version < php 5.3, they can do using timestamps, Like this:

$fdate = $request->Fdate;
$tdate = $request->Tdate;
$datetime1 = strtotime($fdate); // convert to timestamps
$datetime2 = strtotime($tdate); // convert to timestamps
$days = (int)(($datetime2 - $datetime1)/86400); // will give the difference in days , 86400 is the timestamp difference of a day




回答4:


$from=Carbon::now()->subDays(5)->toDateString();

$current=Carbon::now()->toDateString();

$peoples= People::whereBetween('joiningdate',array($diff,$current))->get();


来源:https://stackoverflow.com/questions/41443987/finding-days-between-two-dates-in-laravel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!