Reputation: 1868
I have a funtion to get days remaining before a Start Date. I'm using Carbon to handle this in my model like this:
public function getDaysRemainingForFirstPaymentAttribute()
{
if (Carbon::createFromTimestamp($this->trip_start_date)->subDays(150) >= (Carbon::now())) {
return 'Due on'. ' ' .Carbon::parse($this->trip_start_date)->subDays(150)
->format('m-d-Y').' | '.Carbon::now()
->diffInDays(Carbon::create($this->trip_start_date)
->subDays(150), false) . ' ' . 'days';
} else {
return 'Due Now';
}
}
//IN MY IF, I have tried:
//if (Carbon::create(...
//if (Carbon::parse(...
When I Die Dump on $this->trip_start_date
I get the following date:
Illuminate\Support\Carbon @1582347600 {#1006 ▼
date: 2020-02-22 00:00:00.0 America/New_York (-05:00)
}
Then my error is:
Carbon could not be converted to int
Upvotes: 0
Views: 936
Reputation: 9069
You already have $this->trip_start_date
as a Carbon instance and no need to use Carbon::createFromTimestamp
:
if ($this->trip_start_date->subDays(150) >= Carbon::now()) {
return 'Due on'. ' ' .$this->trip_start_date->subDays(150)
->format('m-d-Y').' | '.Carbon::now()
->diffInDays($this->trip_start_date
->subDays(150), false) . ' ' . 'days';
}
You Can also use Carbon Comparison functions:
if ($this->trip_start_date->subDays(150)->gte(Carbon::now())) {
return sprintf("Due on %s | %s days",
$this->trip_start_date->subDays(150)->format('m-d-Y'),
Carbon::now()->diffInDays($this->trip_start_date->subDays(150), false)
);
}
Upvotes: 1