How do I calculate age using php and html?

Asked

Viewed 7,512 times

-1

Using the data from html in the php how to calculate age?

Date of birth on HTML:

<form method="POST" action="doc.php">
   Nascimento: <input type="date" id="data" name="data">
</form>

In the php I call the date:

<?php
     echo $_POST['data']; 
     //a data digitada no formulario html
     //eh exibida no formato yyyy/mm/dd 
?>

Now I use the function date to know the current date, then I must create the variable $idade. How to perform the calculation with this data?

<?php
$dataNasc = $_POST['data'];
$dataAtual = date('Y/m/d');
//portanto, como ficaria a variável idade?
$idade = ?;

    echo "Idade é: $idade Anos";
?>
  • I took a look, it wasn’t quite that

  • 1

    What is the difference? The question appears to be exactly the same, the date input (at least in Chrome and Edge) already in the format YYYY-MM-DD, which is compatible with the answers to the question I mentioned

  • You want to calculate age and the quoted question explicitly does that. I can’t see how it wouldn’t be duplicate.

  • Solved, Thanks !

1 answer

1

//Resolvi:
<?php
     $data = $_POST['data'];

    // separando yyyy, mm, ddd
    list($ano, $mes, $dia) = explode('-', $data);

    // data atual
    $hoje = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
    // Descobre a unix timestamp da data de nascimento do fulano
    $nascimento = mktime( 0, 0, 0, $mes, $dia, $ano);

    // cálculo
    $idade = floor((((($hoje - $nascimento) / 60) / 60) / 24) / 365.25);
     echo "Idade: $idade Anos";
    ?>

output:

inserir a descrição da imagem aqui

  • Welcome to Stackoverflow. This question already existed on the site and had an answer. Therefore, in these cases I suggest a search before publishing a duplicate question, or even an answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.