Calculate user age by registered birth date

Asked

Viewed 111 times

1

Good day, late or night

I have the following question: How can I take the birth date of a registered user and make a calculation to know his age today?

If the user is under 18 years for example, he will not be able to access the purchase page of a certain product (regardless of age the user needs to be logged in to be able to access the purchase page).

The code at the moment is like this:

<?php
date_default_timezone_set('America/Sao_Paulo'); // Hora oficial do Brasil.

include_once("../../pagina_de_cadastro/conecta_banco.php"); //Faz a conexao e seleciona o BD  
$select = "SELECT data_nasc FROM usuarios"; // Pegamos o conteudo do banco.  

$data_inicial = DateTime::createFromFormat('y/m/d', 'data_nasc'); //A data do banco deve esta no formato dia/mês/ano
$data_final = date('y/m/d'); // Salva o timestamp atual numa variável

$diferenca = $data_final - $data_inicial;

echo $diferenca;

if ($diferenca < 18) {
    echo '<p style="font-size:300px"> IDADE INSUFICIENTE </p>';
}
  • @fernandosavio believe that the fact that the language is different is not characterized as duplicate, no?

  • My fault, as has the JS tag ended up precipitating me.

  • The duplicate is of this.

1 answer

0

A good alternative to solve your problem is to use the diff method of the class Datetime, it receives a Datetime object and returns another object containing the difference, in the example below you access the difference in years, through the attribute y

function getAge($date){
        $from = new DateTime($date);
        $to   = new DateTime('today');
        return $from->diff($to)->y;
};

$age = getAge('1994-02-01');
  • I tested it here and it really works ,but how can I call the field with the bank’s birth date?

  • @Ellysonvissotto welcome to the community my friend, try to solve one problem at a time, and when post your doubts here try to enrich with details of its implementation, so that we can help you.

Browser other questions tagged

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