Calculate user's age by registered date of birth [duplicate]

1

Good morning, afternoon or evening

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

If you are under 18, for example, you will not be able to access the purchase page for a certain product (regardless of age, the user must be logged in to access the purchase page).

The code at the moment looks 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>';
}
    
asked by anonymous 29.11.2018 / 19:49

1 answer

0

A good alternative to solve your problem is to use the diff method of the DateTime class, 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');
    
29.11.2018 / 19:58