-1

I need to check if 2 different format date strings is a valid dates. The formats are: YYYY-MM-DD and YYYY.MM.DD. I found just only one date string format validation, like so:

function validateDate($date)
{
    $d = DateTime::createFromFormat('Y-m-d', $date);
    return $d && $d->format('Y-m-d') == $date;
}

function was copied from this answer or php.net

But how about two date formats validation? How to solve it? Thanks for any help

Glavić
  • 42,781
  • 13
  • 77
  • 107
HarryFlopper
  • 195
  • 1
  • 2
  • 10

2 Answers2

1

Try the following for both:

$date="2017-09-11";

if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date)) {
    echo true;
} else {
    echo false;
}

$date="2017.10.22";

if (preg_match("/^[0-9]{4}.(0[1-9]|1[0-2]).(0[1-9]|[1-2][0-9]|3[0-1])$/",$date)) {
    echo true;
} else {
    echo false;
}

It uses regex to check if the format is valid or not.

OR

$date="2017-09-11";
$dt = DateTime::createFromFormat("Y-m-d", $date);
echo  $dt !== false && !array_sum($dt->getLastErrors());


$date="2017.10.22";

$dt = DateTime::createFromFormat("Y.m.d", $date);
echo  $dt !== false && !array_sum($dt->getLastErrors());

It uses DateTime to check the date against both formats.

Edit: While both are decent solutions, benchmarks show that in this case, preg_match is considerably faster than DateTime. https://3v4l.org/H8C73

mega6382
  • 9,211
  • 17
  • 48
  • 69
0

Copy the original function, where you specify format as 2nd parameter, and then run function twice; as already mentioned in the comments.

function validateDate($date, $format = 'Y-m-d H:i:s')
{
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

$isValid = validDate($date, 'Y-m-d') || validDate($date, 'Y.m.d');

function was copied from this answer or php.net

Glavić
  • 42,781
  • 13
  • 77
  • 107