NemoBlack
NemoBlack

Reputation: 153

Validation Error dates PHP

I'm trying to validate dates in PHP, but the problem is that with some dates work, an example would be: "02/2/2015" returns true, "20/12/2015" false returns, is a serious problem and I see no error in the code.

Function.

<?php

function check_date($date) {
    $open_date  = explode('/', $date);
    if (count($open_date) == 3) {
        if (checkdate($open_date[0], $open_date[1], $open_date[2])) {
            return true;
        } else {
         return false;
        }
    } else {
        return false;
    }
}

//$date = "02/2/2015"; // return true !
$date = "20/12/2015"; // return false ?

if(check_date($date)) {
    echo "valid";
} else {
    echo "invalid";
}

?>

How could solve this problem?

Upvotes: 0

Views: 21

Answers (2)

Mathew Tinsley
Mathew Tinsley

Reputation: 6976

checkdate expects a month, day and year, in that order:

https://secure.php.net/manual/en/function.checkdate.php

If your dates are formatted as day/month/year then you can still use checkdate, you'll just have to change the order of the parameters:

if (checkdate($open_date[1], $open_date[0], $open_date[2]))

Upvotes: 1

Kamal Soni
Kamal Soni

Reputation: 1552

The signature of checkdate function looks like checkdate(month,day,year); . You can have upto 12 months and not 20. :-)

Upvotes: 0

Related Questions