You can use the DateTime class to easily manipulate dates. I have put the $dateFormat
outside of the method because you could also use that to validate your input in setBirthDate
if you saw fit.
protected $dateFormat="m/d/Y";
public function getAge()
{
// Create a DateTime object from the expected format
return DateTime::createFromFormat($this->dateFormat, $this->birthDate)
// Compare it with now and get a DateInterval object
->diff(new DateTime('now'))
// Take the years from the DateInterval object
->y;
}
Note that I used m/d/Y
for the date format because as per the comments, the mm/dd/yyyy
does not do what you expect. For example, Y is a 4 digit year.
Ignore the ugly syntax, it’s just so I could explain what each bit does.
3
solved Doing Age Calculations via OOP [closed]