Comparing two dates in blade.php file

5.1k views Asked by At

I have to compare two dates in a list.blade.php like

if today's date is greater than or equal to expiry date then do something else do something.

here is the code:

@php
use Carbon\Carbon;
$today_date = Carbon::today();
@endphp

@foreach ($entries as $k => $entry)
@if($today_date >= $entry->expire_date)
// do something
@else 
// do something
@endif
@endforeach

Date format: YYYY-MM-DD

But this is not working.

Please help

Thanks

EDIT:

I tried this:

<?php
    use Carbon\Carbon;
    $today_date = Carbon::now();

    foreach ($entries as $k => $entry) {
        $expire_date = Carbon::createFromFormat('Y-m-d', $entry->expire_date);
    }
?>

and it gives me error like: image

One more thing expire_date is of text type in my database so this might be the problem.

5

There are 5 answers

3
Sreejith BS On BEST ANSWER
@php
    use Carbon\Carbon;
    $today_date = Carbon::now();

    foreach ($entries as $k => $entry) {
        $expire_date = Carbon::createFromFormat('Y-m-d', $entry->expire_date);
        $data_difference = $today_date->diffInDays($expire_date, false);  //false param

        if($data_difference > 0) {
            //not expired
        }
        elseif($data_difference < 0) {
            //expired
        } else {
            //today
        }
    }

@endphp

The false parameter is optional and indicates if you want the return value to be the absolute value or a relative value that might have a - (negative) sign if the passed in date is less than the current instance. This will default to true, return the absolute value.

More here

2
Divyesh Patel On

Use This => Carbon::now();

and format your date as your format(YYYY-MM-DD). Store that date in var and compare that var to expiry date.

There problem in your today_date format.

today_date give a date and time both.

4
aynber On

Since expire_date is text, you'll need to convert it. Luckily, with Carbon, it's easy to do:

$expire_date = Carbon::createFromFormat('Y-m-d', $entry->expire_date);

Then you can use it to compare

@if($today_date->gte($expire_date))

You may want to make sure that $expire_date is not null and does not throw any errors first. It would also be easier if you stored your dates in the database as a date or date time column, to make sure its always in a correct format, and you can also add it as a timestamp in your model, or apply Carbon as an accessor function.

1
parpar On

You need to format your Cabon date object first to match the date(string) value from your DB data.

@if($today_date->format("Y-m-d") >= $entry->expire_date)

It gets printed because your PHP tag is wrong.. missing "?", should be <?PHP

0
yunus kibebu On
@php
    use Carbon\Carbon;
    $today_date = Carbon::now();
    @foreach ($entries as $k => $entry)
@if($entry->expire_date < $today_date)
<p> Expired Date </p>
@else
<p> Expired</p>      
</p>
@endif
@endphp