Check if variable is a valid date with PHP

Alex picture Alex · May 21, 2012 · Viewed 71.2k times · Source

I am working on a script that will import some data from a CSV file. As I am doing this I want to be able to check a variable to see if it is a valid date string.

I have seen several ways to check if a sting is a date, but most of them require you to now the format. I will not know the format that the date will in.

right now I am using strtotime(), but this fails to easily

$field ="May";
if(strtotime($field)){
    echo "This is a date";
}

In this case, "May" was the persons first name, and not a date at all.

Can any one recommend more reliable function?

Edit based on questions from some of you.

For a variable to pass as a "date" in my case, it would need to be specific to a day/month/year, so just "May" would be to vague to count.

Based on that and Pauls good point below we can also test to see if the string contains a number, such as

$field ="May";
if(strtotime($field) && 1 === preg_match('~[0-9]~', $field)){
    echo "This is a date";
}else{
    echo "Nope not a date";
}

This seems to cover my immediate needs, but can any one spot any issues or suggest improvements?

Answer

saluce picture saluce · May 21, 2012

Use date_parse and check the values of the returned array

$date = date_parse("May")

// ["year"] == FALSE
// ["month"] == 5
// ["day"] == FALSE

You can also pass those into checkdate.

$date = date_parse($someString);
if ($date["error_count"] == 0 && checkdate($date["month"], $date["day"], $date["year"]))
    echo "Valid date";
else
    echo "Invalid date";