如何使用碳将年更改为月?

how to change years to months using carbon?

我刚开始使用 Carbon,我能够使程序从给定日期开始计算年份。但是现在我想让格式计算月份,这是我的代码:

public function getAgeAttribute() {   
    return Carbon::parse($this->attributes['emp_birth_date'])->age;
}

我尝试使用代码:

->format('months');

但是出现了一个错误,我不知道它在哪里工作。谁能帮帮我?

没有以月为单位获取年龄的内置方法,但解决起来应该非常简单:

$ageInYears = \Carbon\Carbon::parse($birthday)->age;
$ageInMonths = $ageInYears * 12;

这并不完美,因为年龄不会以小数形式返回,因此 10 年可能介于 120 到 131 个月之间。

如果你想要更准确的东西,你可以像这样使用diffInMonths

$ageInMonths = \Carbon\Carbon::now()->diffInMonths(\Carbon\Carbon::parse($birthday));

此外,->format("months"); 无效,因为 "months" 不是有效的 PHP 日期格式。此外,->format("m")(这是正确的值)在 ->age 上不起作用,因为 ->age returns 是 int,而不是 Carbon 日期。

有关所有可用的 PHP 日期格式选项,请参阅 http://php.net/manual/en/function.date.php