Subtract dates as string in PHP (Object Orientation)

Question:

Starting from a Student class , with a method I am_older_of_age() that returns a boolean , I need to subtract two dates (strings) whose format is the following "Ymd" (That is, an example "2019-04-27").

The dates I need to subtract is the year of the student's birth, in the same format. With the current date (Also in the same format).

Starting from a simple test in an index.php in Apache, I did the following:

<?php

$fechaNacimiento="1993-03-30";
$fechaActual=date("Y")."-".date("m")."-".date("d");

$resultado = $fechaActual-$fechaNacimiento;

//El resultado es "26 años".
echo($resultado." años");

?>


But in the program that I tried to implement the above, it gave me an error in the tests when trying to subtract dates in that way. To do this, I managed to do it without errors as follows (It works):

public function soy_mayor_de_edad(): bool{

         //Obtengo la fecha del propio alumno.
         //Es un string "Y-m-d" resultado de una consulta a una base de datos.
         $fechaNacimiento=$this->nacimiento;

         //Convierto la fecha a un string sin los guiones.              
         $fechaNacimientoInt=$fechaNacimiento[0].$fechaNacimiento[1].$fechaNacimiento[2].$fechaNacimiento[3].$fechaNacimiento[5].$fechaNacimiento[6].$fechaNacimiento[8].$fechaNacimiento[9];

         //Convierto la fecha a un entero para poder restarla.
         $fechaNacimientoInt=(int)$fechaNacimientoInt;


         //Hago lo mismo con la fecha actual.
         $fechaActual=(date("Y")."-".date("m")."-".date("d"));
         $fechaActualInt=$fechaActual[0].$fechaActual[1].$fechaActual[2].$fechaActual[3].$fechaActual[5].$fechaActual[6].$fechaActual[8].$fechaActual[9];
         $fechaActualInt=(int)$fechaActualInt;

         //El resultado (la resta) es un numero entero, 
         //cuyos dos numeros principales serán los años.
         $resultado=$fechaActualInt-$fechaNacimientoInt;

        //En el siguiente numero hay un pequeño problema. 
        //Si es un numero de 6 digitos,  
        //los dos primeros numeros son los años que tiene,
        // pero si es de 5 digitos, solo es el primero numero.

        $resultado=(string)$resultado;
        //Por lo tanto tengo que contar los digitos que tiene el numero, y dependiendo de si son 5 o 6, debo obtener los dos primeros o el primer numero
        if(strlen($resultado)==6){
                $resultadoInt=$resultado[0].$resultado[1];
                $resultadoInt=(int)$resultadoInt;
        }else{
                $resultadoInt=$resultado[0];
                $resultadoInt=(int)$resultadoInt;
        }

        //Si el resultado es menor a 18, es menor, si no, es mayor de edad.
        if($resultadoInt<18){
                return False;
        }else{
                return True;
        }
}

I would like to know if it can be achieved in a simpler and cleaner way, without the need for so much code or performing so many operations. Bearing in mind that the student's date of birth is a string in "Ymd" format since it is the result of a query to a database.

Answer:

One way you can do it is as follows:

We take the date of birth:

$nacimiento= new DateTime("1993-03-30);

Now the current date:

$hoy = new DateTime();

With the PHP diff function we calculate the age:

$anios= $hoy->diff($nacimiento);

The result of this:

echo $anios->y; //26 años

Full example could be like this:

public function soy_mayor_de_edad(): bool{

    $nacimiento= new DateTime("1993-03-30");
    $hoy = new DateTime();
    $anios= $hoy->diff($nacimiento);

    return $anios->y < 18; //Devolverá al método true o false
}
Scroll to Top