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

Asked

Viewed 1,472 times

3

the question gets even harder:

the field data_cadastro is as sweep, I have several tables and each one of them has a different type of date, for example: in a table there:

  • 2015-12-01;

in the other:

  • 12/07/2015;

and in another:

  • 14-05-2015

etc....

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

  • Assuming there are no 2-digit years, you could check whether the 3rd character is a slash or a dash. If it is, you have the date in the format dd/MM/yyyy or dd-mm-yyyy. I think there must be some other way, but on the face, I don’t know.

  • There are several examples of SQL statements that allow updating the column value to a given format (str_to_date). When finished, just change the column to Datetime

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
  • I suggest creating a new column in your date database and normalizing it using a script. ;)

1

Another way using 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

Browser other questions tagged

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