Validate a date in PHP

0

Good, I am trying to verify, rather validate, that the date of birth that the user provides me is less than the current date of the system.

Could someone help me? Thank you very much.

    
asked by owenjr 30.11.2017 в 03:45
source

2 answers

1

You can use the function PHP called strtotime

  

Here the link of the documentation > Strtotime

Here is an example of this method in execution ...

<?php
    date_default_timezone_set("America/Mexico_City");
    $end = '2017-12-29';
    $fecha_actual = strtotime(date("Y-m-d H:i:s"));
    $fecha_nacimiento = strtotime($end);
        
        if($fecha_actual > $fecha_nacimiento){
            echo "fecha correcta";
        }else{
            echo "fecha incorrecta";
        }                   
?>

With date_default_timezone_set we set the time zone (I put it since several times PHP returns me incorrect hours even if my php.ini has correctly set the zone)

In the variable $end we establish the date of birth, which may well be received from a form with $end = $_POST['idElementoDondeSeIngresaLaFechaDeNacimiento'];

In the variable $fecha_actual we collect the date with format year-month (number) -dia (number) hour (with 24 hour format) -minutes-seconds

And the if simply compares both variables, I hope it serves you, greetings.

    
answered by 30.11.2017 / 04:52
source
0

If you are more specific about how you received the date, it could be more explicit but I leave this:

$fecha_recibida = $_POST['fecha']; //Tiene que estar en el formato 2017-11-29
$fecha_enviada = new DateTime(date('Y-m-d',$fecha_recibida));
$fecha_actual = new DateTime(date('Y-m-d'));

if ($fecha_actual > $fecha_enviada) {
    # code
}
    
answered by 30.11.2017 в 04:54