How to get difference between two dates in Laravel?

In this post, we will focus on how to get difference between two dates in Laravel. This is a simple example of how to calculate the difference between two dates in Laravel. You will learn how to get difference between two dates in Laravel using the Carbon library.

How to get difference between two dates in Laravel

When working with dates in Laravel, you may often need to calculate the difference between two dates. Laravel uses the powerful Carbon library, which provides various methods to handle date differences effectively.

In this post, we will explore different methods to calculate date differences, including differences in days, months and years.

To achieve this, we will use the following Carbon functions:

  • diffInDays(): To get the difference in days.
  • diffInMonths(): To get the difference in months.
  • diffInYears(): To get the difference in years.

Let’see the example below.

Example 1: Calculate difference in Days
<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;


class DemoController extends Controller
{

    public function index()
    {
       $toDate = Carbon::parse("2022-08-12");
       $fromDate = Carbon::parse("2022-08-16");

       $days = $toDate->diffInDays($fromDate);

       print_r("Differnce Days: ". $days);
    }
}
Output:
Differnce Days: 4
Example 2: Calculate difference in Months
<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;


class DemoController extends Controller
{

    public function index()
    {
       $toDate = Carbon::parse("2022-08-12");
       $fromDate = Carbon::parse("2022-09-16");

       $months = $toDate->diffInMonths($fromDate);    

       print_r("Differnce Months: ". $months);
    }
}
Output:
Differnce Months: 1
Example 3: Calculate difference in Years
<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;


class DemoController extends Controller
{

    public function index()
    {
       $toDate = Carbon::parse("2022-08-12");
       $fromDate = Carbon::parse("2023-09-16");

       $years = $toDate->diffInYears($fromDate);    

       print_r("Differnce Months: ". $years);
    }
}
Output:
Differnce Years: 1

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *