how to calculate age of a person with carbon in laravel?

1

Greetings I have the following code:

$anios=\Carbon\Carbon::parse($paciente->fecha_nacimiento)->age;

That basically calculates my age well, but this age is calculated with the current date.

  

How do I calculate the age for previous years or who just arrived?

That is, calculate the age of someone born in 1990 to 2011, for example, or of the same person born in 1990 until 2046?

  

Also, how to calculate the age of a newborn person in months?

for example: the person was born in September 2018 and calculate it until January 2019?

    
asked by Shassain 02.12.2018 в 04:05
source

1 answer

1

CASE 1

This way you can calculate the age of a person knowing when he was born and using the current date

$nacimiento = "1989-04-06 06:00:00";
$actual = Carbon::now();

return $actual->diffForHumans($nacimiento, $actual);

//dará 29 años como resultado

CASE 2

To calculate the age of a person given his date of birth and any date different from the current one; it works like this

$nacimiento = "1989-04-06 06:00:00";
$actual = Carbon::parse("2011-12-05 06:00:00");

return $actual->diffForHumans($nacimiento, $actual);

//dará 22 años como resultado
  

We use Carbon::parse() so that the string you pass is formatted to a valid date format.

CASE 3

To obtain the difference of months between 2 dates, you could use diffInMonths() and build your code something similar to this

$nacimiento = "2018-09-01 06:00:00";
$actual = Carbon::parse("2019-01-01 06:00:00");
return $actual->diffInMonths($nacimiento);

//lo cual me dará la diferencia de 4 meses entre una fecha y otra
    
answered by 02.12.2018 / 04:31
source