How to correctly determine if a date string is a valid date in that format in PHP?

Spread the love

Sometimes, we want to correctly determine if a date string is a valid date in that format in PHP.

In this article, we’ll look at how to correctly determine if a date string is a valid date in that format in PHP.

How to correctly determine if a date string is a valid date in that format in PHP?

To correctly determine if a date string is a valid date in that format in PHP, wwe can check if we can format the string into a date.

For instance, we write

function validateDate($date, $format = "Y-m-d")
{
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) === $date;
}

var_dump(validateDate("2022-12-01"));

to define the validateDate function.

In it, we call DateTime::createFromFormat with $format and $date to create the$d date time format object.

Then we call $d->format($format) to return the formatted version of $d in the $format format and check that it’s the same as $date.

Conclusion

To correctly determine if a date string is a valid date in that format in PHP, wwe can check if we can format the string into a date.

Leave a Reply

Your email address will not be published.