我刚开始使用 Carbon ,我能够让程序在计算给定日期的年份 . 但现在我想让格式计算几个月,这是我的代码:
Carbon
public function getAgeAttribute() { return Carbon::parse($this->attributes['emp_birth_date'])->age; }
我尝试使用代码:
->format('months');
但得到一个错误,我不知道它在哪里工作 . 谁能帮我?
在Months中没有内置的获取年龄的方法,但解决起来应该很简单:
$ageInYears = \Carbon\Carbon::parse($birthday)->age; $ageInMonths = $ageInYears * 12;
这并不完美,因为年龄不会以小数形式返回,因此10年可能在120到131个月之间 .
如果你想要更准确的东西,你可以像这样使用 diffInMonths :
diffInMonths
$ageInMonths = \Carbon\Carbon::now()->diffInMonths(\Carbon\Carbon::parse($birthday));
此外, ->format("months"); 无效,因为 "months" 不是有效的PHP日期格式 . 另外, ->format("m") (这是正确的值)在 ->age 上不起作用,因为 ->age 返回 int ,而不是 Carbon 日期 .
->format("months");
"months"
->format("m")
->age
int
有关所有可用的PHP日期格式选项,请参阅http://php.net/manual/en/function.date.php .
1 回答
在Months中没有内置的获取年龄的方法,但解决起来应该很简单:
这并不完美,因为年龄不会以小数形式返回,因此10年可能在120到131个月之间 .
如果你想要更准确的东西,你可以像这样使用
diffInMonths
:此外,
->format("months");
无效,因为"months"
不是有效的PHP日期格式 . 另外,->format("m")
(这是正确的值)在->age
上不起作用,因为->age
返回int
,而不是Carbon
日期 .有关所有可用的PHP日期格式选项,请参阅http://php.net/manual/en/function.date.php .