如何修复:Carbon 无法转换为 int

How to fix: Carbon could not be converted to int

我有一个函数可以获取开始日期之前的剩余天数。我在我的模型中使用 Carbon 来处理这个问题:

    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(...

当我在 $this->trip_start_date Die Dump 时,我得到以下日期:

Illuminate\Support\Carbon @1582347600 {#1006 ▼
  date: 2020-02-22 00:00:00.0 America/New_York (-05:00)
}

那么我的错误是:

Carbon could not be converted to int

您已经将 $this->trip_start_date 作为 Carbon 实例,无需使用 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';
}

您还可以使用 Carbon Comparison 函数:

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)
    );
}