I have a date in the form DD-MM-YYYY, I know how to explode it into just DD, MM and YYYY on its own but how do I check if this date is valid? For example 01-02-2009 is valid but 31-02-2009 is not.

Any way to check this?

Dani AI

Generated

Good — 's quick fix sorted it for . For cases where you need stricter checks (exact DD-MM-YYYY format, reject forgiving conversions, or enforce year ranges), use a format-aware parser and explicit error checks rather than relying on loose parsing.

A reliable pattern is to parse with DateTime::createFromFormat and then confirm there were no errors or warnings and that the formatted result matches the original input. That avoids cases where invalid dates get adjusted into valid ones. Example:

$date = '31-02-2009';
$d = DateTime::createFromFormat('d-m-Y', $date);
$errors = DateTime::getLastErrors();

if ($d && $errors['warning_count'] === 0 && $errors['error_count'] === 0 && $d->format('d-m-Y') === $date) {
    // valid date
} else {
    // invalid date
}

Do a quick regex pre-check to enforce the exact digit counts before parsing:

if (preg_match('/^\d{2}-\d{2}-\d{4}$/', $date)) { /* then parse as above */ }

If you want to accept non-zero-padded input like 1-2-2009, use \d{1,2} in the regex and parse with j-n-Y instead of d-m-Y.

Watch for common edge cases: leap years (Feb 29), leading/trailing whitespace, and desired year limits (check numeric year range after parsing). Time zones are irrelevant for pure date checks. See the PHP docs for parsing and error reporting: DateTime::createFromFormat and DateTime::getLastErrors.

Recommended Answers

All 3 Replies

Member Avatar for Member #120589

checkdate($m,$d,$y) will check a date. If you've already exploded - easy.

Ahh fixed thanks a lot :)

Member Avatar for Member #120589

Are we solved then?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.