ali dehqani
ali dehqani

Reputation: 184

How to calculate a few days left or the last few days in Carbon

I have ExpireDate, NowTime fields in my table like example:

Expire Date : 2020-05-11 00:00:00
NowTime :     2020-05-13 00:00:00

I want to get to the difference between the two dates (NowTime - ExpireDate) and use this code:

$diff=Carbon::now()->diffInDays($row->expire_date);

The problem is that if there are two days left until the expiration date, Carbon return 2, Also, if 2 days have passed since the date Carbon return 2

How can I detect if it's 2 days left or 2 days passed of date?

Upvotes: 2

Views: 2849

Answers (2)

KyleK
KyleK

Reputation: 5131

You can use the following tools:

Carbon::now()->diffInDays($row->expire_date, false) // negative number if expired_date is over
Carbon::now()->isAfter($row->expire_date) // true if expired_date is over

Upvotes: 4

Gowsegan
Gowsegan

Reputation: 69

Laravel 5.*, you just try diffForHumans() method. It's no needed to the current date. The result will be display second, minutes, hour, week, month, year ago.

$diff = $row->expire_date->diffForHumans();

echo $row->expire_date->diffForHumans(); // a second ago 
echo $row->expire_date->diffForHumans(); // 10 hour ago
echo $row->expire_date->diffForHumans(); // 5 days ago
echo $row->expire_date->diffForHumans(); // 1 week ago
echo $row->expire_date->diffForHumans(); // 4 month ago
echo $row->expire_date->diffForHumans(); // 2 year ago

If you need to use Carbon method try this..

{{ Carbon\Carbon::parse($row->expire_date)->diffForHumans()}}

Upvotes: 2

Related Questions