Laravel Get difference between two dates in days using Carbon

  1363 views   6 months ago Laravel

In any web application, admin panel has report generate module. When generating reports, you might want to get number of days between two dates. Laravel uses carbon package for comparing dates.

In this article, I will share you how you can get different between two dates in Laravel using Carbon. Carbon diffInDays() method returns different between two dates in number of days.

Laravel comes Carbon preinstalled. You don't need to install Carbon. Just import class before you use it. Below example shows how you can do it:

use \Carbon\Carbon;

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Support\View
 */
public function index()
{
    $start_date = Carbon::createFromFormat('d-m-Y', '1-2-2020');
    $end_date = Carbon::createFromFormat('d-m-Y', '1-3-2020');

    $different_days = $start_date->diffInDays($end_date);

    return $different_days; // 13
}

Carbon also consider leap year, so you don't need to consider the leap year. Here is the difference:

/**
 * get segment from url
 *
 * @return $this
 */
public function currentUrl()
{
    // normal year
    $start_date = Carbon::createFromFormat('d-m-Y', '1-2-2021');
    $end_date = Carbon::createFromFormat('d-m-Y', '1-3-2021');

    $different_days = $start_date->diffInDays($end_date); // 28

    // leap year
    $start_date = Carbon::createFromFormat('d-m-Y', '1-2-2020');
    $end_date = Carbon::createFromFormat('d-m-Y', '1-3-2020');

    $different_days = $start_date->diffInDays($end_date); // 29
}

I hope you liked the article and help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]