calculate the age from the date of birth with the datepicker class [duplicated]

5

I would like to calculate the age of a user from his date of birth, so that when the date of birth is entered in:

<input type="date" name="fecha_nacimiento" id="fecha_nacimiento" class="datepicker" />

and it automatically loads in the

<input type="text" name="edad"  id="edad" value="<?php echo $edad;?>" readonly="true"/>

But I do not get it, I currently have this:

<?
function edad($fecha_nacimiento) { 
    $tiempo = strtotime($fecha); 
    $ahora = time(); 
    $edad = ($ahora-$tiempo)/(60*60*24*365.25); 
    $edad = floor($edad); 
    return $edad; 
} 
?>

The datepicker format is format: 'yyyy-mm-dd' // foramto de fecha

    
asked by yoclens 06.04.2017 в 22:09
source

2 answers

4

I believe that one of the easiest ways to calculate age is by obtaining the difference in years directly from the current date to the birthday date with the function diff .

However, for the DateTime to work correctly you will have to indicate the months first and then the day. In other words, if you were born on September 25, 1954, it would have to be 09/25/1954.

On the other hand, as @jotaelesalinas has indicated, a much more intuitive format that you can use in almost all DateTime (I say almost all in case there is one that does not, the truth that I do not know ) is the YYYY-MM-DD format. In this way it is much easier to detect the day and month in a much faster way without confusion.

<?php
    $cumpleanos = new DateTime("1982-06-03");
    $hoy = new DateTime();
    $annos = $hoy->diff($cumpleanos);
    echo $annos->y;

Demo .

    
answered by 06.04.2017 в 22:43
1

I think it can help you, I have this function that gives you back the age

function busca_edad($fecha_nacimiento){
$dia=date("d");
$mes=date("m");
$ano=date("Y");


$dianaz=date("d",strtotime($fecha_nacimiento));
$mesnaz=date("m",strtotime($fecha_nacimiento));
$anonaz=date("Y",strtotime($fecha_nacimiento));


//si el mes es el mismo pero el día inferior aun no ha cumplido años, le quitaremos un año al actual

if (($mesnaz == $mes) && ($dianaz > $dia)) {
$ano=($ano-1); }

//si el mes es superior al actual tampoco habrá cumplido años, por eso le quitamos un año al actual

if ($mesnaz > $mes) {
$ano=($ano-1);}

 //ya no habría mas condiciones, ahora simplemente restamos los años y mostramos el resultado como su edad

$edad=($ano-$anonaz);


return $edad;


}
    
answered by 06.04.2017 в 23:38