Check if a string is a date in PHP

3

I am receiving two dates from a form, I am in the validation process on the server. How do I validate the string if it is a valid date? I have now decomposed the date in an array $fecha_array = explode('-', $fecha); and I have highlighted a count($fecha_array) to verify that the array has 3 data, and finally verify that it is a date valid with checkdate($fecha_array[0], $fecha_array[1], $fecha_array[2]) the format used is mm-dd-yyyy . Up there all the problem arises when I try with the following: 01-gg-2019 , I know that gg is not a day, but that's what validation is about. thanks for your help. the error that comes out is gg is not integer checkdate() expects parameter 1 to be integer, string given

    
asked by César Rodríguez Reyes 02.01.2019 в 18:08
source

3 answers

2

A very simple approach is to check if it is a valid date in php with date.

function check($x) {
    if (date('d-m-Y', strtotime($x)) == $x) {
      return true;
    } else {
      return false;
    }
}

Origin here link

    
answered by 02.01.2019 в 21:44
2

Well you have two ways to validate the date or at least based on what you are looking for:

  

Appointment Edited to validate ranges of the date between 1-31, 1-12 and the year range

    $fecha_entrante = "mi fecha es 31-02-2019"; 
function validados($fecha){
    preg_match('/(\d{1,2})+(-)+(\d{2})+(-)+(\d{4})/', $fecha, $salida);
    if(count($salida)>=1){
        $salida = array_values(array_diff($salida,['-']));
        if(!in_array($salida[2],range(1,12))){ return false; }
        if(!in_array($salida[3],range(1900,2500))){ return false; }
        if(!in_array($salida[1],range(1,cal_days_in_month(CAL_GREGORIAN, $salida[2], $salida[3])))){ return false; }
        return true;
    }else{
        return false;
    }
}

this executes the same work, but it also serves you not only to validate the date but also to extract them from a complete text string.

I hope it serves you. Greetings

    
answered by 02.01.2019 в 19:07
1

Trying to follow your idea, I think it should be like this:

$fecha       = '01-rr-2019';
$fecha_array = explode('-', $fecha);
$fechaA      = strtotime($fecha_array[1]."-".$fecha_array[0]."-".$fecha_array[2]);
if($fechaA != "" AND  checkdate(date("m",$fechaA), date("d",$fechaA), date("Y",$fechaA)) === true){
    //coNtinuas tu codigo
    echo "Fecha OK";
}
echo "<br> ".date("Y-m-d",$fechaA);
    
answered by 02.01.2019 в 21:46