Reputation: 47
I just started using Carbon
, I was able to make the program work in computing the years from the given date. But now I want to make the format counting the months, this is my code:
public function getAgeAttribute() {
return Carbon::parse($this->attributes['emp_birth_date'])->age;
}
I tried using the code:
->format('months');
but got an error I don't know where make it work. Can anyone help me?
Upvotes: 2
Views: 1365
Reputation: 29278
There isn't a built-in method for getting age in Months, but it should be pretty simple to solve:
$ageInYears = \Carbon\Carbon::parse($birthday)->age;
$ageInMonths = $ageInYears * 12;
This isn't perfect, as age is not returned as a decimal, so 10 years could be anywhere between 120 and 131 months.
If you want something more accurate, you can use diffInMonths
like so:
$ageInMonths = \Carbon\Carbon::now()->diffInMonths(\Carbon\Carbon::parse($birthday));
Also, ->format("months");
is invalid, as "months"
is not a valid PHP date format. Also also, ->format("m")
(which is the correct value) wouldn't work on ->age
, as ->age
returns an int
, not a Carbon
date.
See http://php.net/manual/en/function.date.php for all the available PHP date formatting options.
Upvotes: 3