how to tell if the date is of the date type yyyy-mm-dd, dd / mm / yyyy etc?

3

The question becomes even more difficult:

The field data_cadastro is like varchar , I have several tables and each one has a different type of date, for example: in a table there is:

  • 2015-12-01;

in the other:

  • 12/07/2015;

and in another:

  • 05-14-2015

etc ...

Is there any way to return if this date is of type yyyy-mm-dd, dd-mm-yyyy, dd / mm / yyyy and vice versa?

    
asked by anonymous 15.07.2015 / 14:36

2 answers

2

You can use regular expressions:

<?php
function DateFormat($date){
   if (preg_match("/\d{4}-\d{2}-\d{2}/", $date))
      return 'YYYY-MM-DD';
   elseif (preg_match("/\d{2}\/\d{2}\/\d{4}/", $date))
      return 'DD/MM/YYYY';
   elseif (preg_match("/\d{2}-\d{2}-\d{4}/", $date))
      return 'DD-MM-YYYY';
   else return FALSE;
}

echo DateFormat('2015-12-01').PHP_EOL;
echo DateFormat('12/07/2015').PHP_EOL;
echo DateFormat('14-05-2015').PHP_EOL;

// Saída
// YYYY-MM-DD
// DD/MM/YYYY
// DD-MM-YYYY
    
15.07.2015 / 14:49
1

Another way to use regular expressions:

$variations = array (
    '^([0-9]{4})/[0-9]{2}/[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{4}2$' => 'Y/m/d H:i:s',
    // Mais outras expressões regulares aqui
);

foreach ($dateFromDatabase as $date) {
    foreach ($variations as $regexp => $dateFormat) {
        if (preg_match ('|' . $regexp . '|', $date)) {
            $matches[$dateFromDatabase] = $dateFormat;
            break;
        }
    }
}
// $matches agora consiste em um array de datas => formato
    
15.07.2015 / 14:53