PoundXI
PoundXI

Reputation: 121

PHP Checking datetime format using preg_match and checkdate wrong result

I want to validate datetime format using preg_match() and checkdate() function. My format is "dd/MM/yyyy hh:mm:ss". What wrong with my code?

function checkDatetime($dateTime){
    $matches = array();
    if(preg_match("/^(\d{2})-(\d{2})-(\d{4}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $dateTime, $matches)){
        print_r($matches); echo "<br>";
        $dd = trim($matches[1]);
        $mm = trim($matches[2]);
        $yy = trim($matches[3]);
        return checkdate($mm, $dd, $yy); // <- Problem here?
    }else{
        echo "wrong format<br>";
        return false;
    }    
} 

//wrong result
if(checkDatetime("12-21-2000 03:04:00")){
    echo "checkDatetime true<br>";
}else{
    echo "checkDatetime false<br>";
}

//correct result
if(checkdate("12", "21", "2000")){
    echo "checkdate true<br>";
}else{
    echo "checkdate false<br>";
}

Output:

Array ( [0] => 12-21-2000 03:04:00 [1] => 12 [2] => 21 [3] => 2000 [4] => 03 [5] => 04 [6] => 00 )

checkDatetime false

checkdate true

Upvotes: 0

Views: 3167

Answers (1)

David Kiger
David Kiger

Reputation: 1996

if(checkDatetime("12-21-2000 03:04:00")) leads to

$dd = 12
$mm = 21
$yy = 2000

You then call return checkdate($mm, $dd, $yy);, which is equivalent to return checkdate(21, 12, 2000);

It's fairly clear that $mm can't be 21, but I can't say if you're passing the wrong format to checkDatetime or if you're parsing it wrong in the regex.

Upvotes: 3

Related Questions