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

Asked

Viewed 1,041 times

3

I’m picking up a date in form and in firefox the DATE field behaves like a normal text field. Ai, if the person type a date in the format dd/mm/yyyy, I have a function that converts this date to save in Mariadb(Mysql). The problem is that in Chrome the date is already formatted, there is no need for this formatting!

What I want to do is check to see if this date already in the right format, because if you are want to ignore 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;

}

2 answers

2


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

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

0

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

  • Invalid Effective Date Format.
  • '; endif;

    I use this function and works perfectly for date input.

    Browser other questions tagged

    You are not signed in. Login or sign up in order to post.