Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

FounderStartup's avatar

Calculate Difference between two dates ?

I need to calculate the number of days between now() and expiry date to get number of days for expiry. My blade is giving incorrect days. Any help ? The code is in a foreach loop.

Blade

			<div class="job-listing-footer">
                                                    @php
                                                        $date1 = now();
                                                        $date2 = $item->expiry_date;
                                                        $difference = $date1->diff($date2);
                                                        $diffInDays = $difference->d;
                                                    @endphp

													<ul>
                                                        @if ($diffInDays==1)
                                                            <li><i class="icon-material-outline-access-time"></i>{{$diffInDays}} day left</li>
                                                            {{-- <div class="countdown green margin-bottom-35">{{$diffInDays}} day left</div> --}}
                                                        @else
                                                            <li><i class="icon-material-outline-access-time"></i>{{$diffInDays}} days left</li>
                                                            {{-- <div class="countdown green margin-bottom-35">{{$diffInDays}} days left</div> --}}
                                                        @endif

													</ul>
												</div>
0 likes
10 replies
alqahtani's avatar

now() gives you the date and time and if it less than 24 hours it subtract the day.

you can use today() instead

1 like
Snapey's avatar

be aware your approach will also return 1 if you are 1 day past expiry

2 likes
alqahtani's avatar
Level 15

@Snapey you can pass false as second argument

$date1 = today();                                                        
$date2 = new \Carbon\Carbon('2022-3-8');
$difference = $date1->diffInDays($date2, false); // -1
1 like
alqahtani's avatar

@FounderStartup

if $date2 less than $date1 the result would be negative -- passed expiry date

if $date2 greater than $date1 the result would be positive

1 like

Please or to participate in this conversation.