Home > front end >  Php check if string contains valid date
Php check if string contains valid date

Time:04-28

I need to validate if string contains valid date/datetime in any of the popular formats, i.e.

2022-01-01
2022/01/01
2022.01.01
2022-01-01 16:00:00
01-01-2022
...

I need this to check whether to create DateTime object from this string, because DateTime seems to work with string dates in strange ways, for example 1981/9132122 is recognised as valid date. I tried to use strtotime and it recognises such string as valid date too. And it seems like regex won't be able to cover all possible date formats. Is there any other ways to check if string contains valid date?

CodePudding user response:

Based on your question, I would go this route

<?php

function isDateValid(string $date): bool
{
    try {
        $newDateTime = new DateTime($date);
    } catch (Throwable $throwable) {
        return false;
    }

    return true;
}

$dates = [
    '2022-01-01',
    '2022/01/01',
    '2022.01.01',
    '2022-01-01 16:00:00',
    '01-01-2022',
    ' 1981/9132122',
];

foreach ($dates as $date) {
    var_dump(isDateValid($date));
}

CodePudding user response:

1- dot is not a valid DateTime. 2- Is not elegant but work for you.

$input = '2022-01-01 16:00:00';
$res = validate($input);
var_dump($res);
function validate($date){
    $check = explode('.', $date);
    if(count($check) == 3) { return true; }
    $check = explode('-', $date);
    if(count($check) == 3) { return true; }
    $check = explode('/', $date);
    if(count($check) == 3) { return true; }
    return false;
}

CodePudding user response:

I recommend to use checkdate() in conjunction with regex but you might have problem with some date format like mm/dd/yyyy or mm/dd/yy.

  • Related