How to compare two date in laravel?

Member

by ryleigh , in category: PHP General , a year ago

How to compare two date in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , a year ago

@ryleigh 

In Laravel, you can use the Carbon library to compare two dates. Here's an example of how to compare two dates in Laravel:

  1. First, make sure you have the Carbon library installed. You can install it using Composer by running the following command in your terminal:
1
composer require nesbot/carbon


  1. Import the Carbon library at the top of your PHP file:
1
use IlluminateSupportCarbon;


  1. Then, you can create two Carbon instances with the dates you want to compare:
1
2
$date1 = Carbon::parse('2022-01-01');
$date2 = Carbon::parse('2022-01-02');


  1. Now, you can use the comparison methods provided by Carbon to compare the two dates:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
if ($date1->eq($date2)) {
    // Dates are equal
}

if ($date1->gt($date2)) {
    // Date 1 is greater than Date 2
}

if ($date1->lt($date2)) {
    // Date 1 is less than Date 2
}

if ($date1->gte($date2)) {
    // Date 1 is greater than or equal to Date 2
}

if ($date1->lte($date2)) {
    // Date 1 is less than or equal to Date 2
}


  1. You can also use the diff method to get the difference between the two dates in days, hours, minutes, etc.:
1
2
3
4
$diff = $date1->diff($date2);
echo $diff->days;  // Difference in days
echo $diff->h;     // Difference in hours
echo $diff->m;     // Difference in minutes


By using the Carbon library and its comparison methods, you can easily compare two dates in Laravel.