How to check if a date is already in the correct format in php?

3

I'm getting a date in form and in firefox the DATE field behaves like a normal text field. Hi, I have a date in the format dd/mm/yyyy , so I have a function that converts this date to save in MariaDB (MySql). The problem is that in chrome the date is already formatted, so it does not need this formatting! >

What I want is to check to see if this date is already in the right format, because if you want to skip the formatting.

follows the function:

function traduz_data_para_banco($parametro){

    if($parametro === null){
        echo "data nula"; 
        return;
    }
    $data_picada = explode("/",$parametro);
    $data_USA = "{$data_picada[2]}" . "-" . "{$data_picada[1]}" . "-" . "{$data_picada[0]}";

    return $data_USA;

}
    
asked by anonymous 11.08.2017 / 15:25

2 answers

2

The best way to validate dates in PHP is by using the DateTime () class. >

I believe that the most important thing is not to check if the date already comes in the American format, but if the user is entering the date correctly

$data = '10/08/2017';
echo validarData($data, 'd/m/Y');

echo PHP_EOL; // Apenas quebra alinha

$data = '2017/08/10';
echo validarData($data, 'Y/m/d');

function validarData($date, $format = 'Y-m-d') {

    $d = DateTime::createFromFormat($format, $date);

    if ($d && $d->format($format) != $date) {
        echo 'Data Inválida';
    }

    return $d->format('Y-m-d');
}

And I always recommend using the function to validate date, even if chrome returns the date in the bank format, because if one day this changes, your system will already be prepared for this change. >     

11.08.2017 / 15:56
0

$ data = explode ('/', $ vigenciac);                 if (! checkdate ($ data [1], $ data [0], $ data [2])):                     $ message. = '

  • Invalid Start Date format.
  • ';                 endif;

    I use this function and it works perfectly for date entry.

        
    14.08.2017 / 01:39