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


I'm getting a date in form and in firefox the DATE field behaves like a normal text field. So, if the person enters a date in dd/mm/yyyy format, I have a function that converts this date to save in MariaDB(MySql). The problem is that in chrome the date is already formatted, then you don't need this formatting!

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

follow function:

function traduz_data_para_banco($parametro){

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

    return $data_USA;



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

I believe that the most important thing is not to check if the date is already in 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 bank format, because if one day this changes, your system will already be prepared for this change.

Scroll to Top