Finding days between two dates in laravel [duplicate]
Asked Answered
C

7

30

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.

Cutworm answered 3/1, 2017 at 12:53 Comment(1)
The actual answer to this question is to do just $start = Carbon::parse($fdate); and $end = Carbon::parse($tdate); By using the Carbon::format() function you got a string, so you would have received an error like "Call to member function diffInDays() on non-object"Harpoon
C
49

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, it's 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.

Cascarilla answered 3/1, 2017 at 13:19 Comment(6)
I am writing this code in a Controller. This code throws an error : Class 'App\Http\Controllers\Admin\DateTime' not found. DateTime works with php.Cutworm
Add use DateTime; at the top of the controller and try again.Cascarilla
Tried that and it worked!. Before, I was using DateTime of Carbon. It didn't helped me. ThanksCutworm
@Kiran Rai Chamling, Please mark the answer as accepted if it helped you to close this thread. ThanksCascarilla
Just in case something went wrong, you can add try { } catch (\Exception $e){} on your DateTime code. Because DateTime class would throw Exception when error occured. Thanks to PHPStorm for reminds me.Thenceforth
This worked for me $datetime1->diff($datetime2)->daysSchizogony
P
21
$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
Pyrostat answered 2/9, 2017 at 5:23 Comment(0)
E
9

Why not use Carbon helper to get the exact date

$to = \Carbon\Carbon::parse($request->to);
$from = \Carbon\Carbon::parse($request->from);

        $years = $to->diffInYears($from);
        $months = $to->diffInMonths($from);
        $weeks = $to->diffInWeeks($from);
        $days = $to->diffInDays($from);
        $hours = $to->diffInHours($from);
        $minutes = $to->diffInMinutes($from);
        $seconds = $to->diffInSeconds($from);
Extinguisher answered 17/11, 2021 at 5:37 Comment(0)
P
4

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

Pleat answered 16/7, 2020 at 6:18 Comment(0)
C
2
$from=Carbon::now()->subDays(5)->toDateString();

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

$peoples= People::whereBetween('joiningdate',array($diff,$current))->get();
Capitulum answered 4/4, 2019 at 13:59 Comment(1)
You need to provide an explanation why your answer addresses the original question. See stackoverflow.com/help/how-to-answerQuechua
H
0
// get from and throung date
$from_date = Carbon::parse(date('Y-m-d', strtotime('2022-03-10'))); 
$through_date = Carbon::parse(date('Y-m-d', strtotime('2022-03-12'))); 
    
// get total number of minutes between from and throung date
$shift_difference = $from_date->diffInDays($through_date);

// will output $shift_difference = 2
Hydrophane answered 10/3, 2022 at 5:42 Comment(0)
G
0

I used this method and it is properly working for me. If you want to verify date of birth with the requested age then use it.

$date_of_birth = Carbon::parse($request->input('student_dob'));
$current_date = Carbon::now();

if ($current_date->diffInYears($date_of_birth) != $request->input('student_age')) {
    return response(['status' => false, 'error' => [
        'student_dob' => ['date of birth not matched with age']
    ]], 500);
}
Gonsalves answered 13/11, 2022 at 6:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.