Finding days between two dates in laravel

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.


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);

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


$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

Tags:

Laravel 5