Check a String is a Valid Date or DateTime format in PHP

darkterminal avatar
GitHub Account@darkterminal
LanguagePHP
Published At2023-05-05 13:05:31

The Back Story about your PHP Metaphor

I writing a story helper (little helper) to validate schema using PHP in my open-source project called SleekwareDB a Flat File database and RESTfull API using SleekDB. I know we have many libraries out there, never mind. It's just freestyled in my old language.

The PHP Story!

You can check if a string is a valid date or datetime format in PHP using the DateTime::createFromFormat() method. This method returns a DateTime object if the input string is a valid date/datetime in the specified format, or false if it is not valid.

Here's an example function that checks whether a string is a valid date or datetime in the given format:

1function isDateTime($dateString, $format) {
2    $dateObj = DateTime::createFromFormat($format, $dateString);
3    return $dateObj !== false && !array_sum($dateObj->getLastErrors());
4}

You can use this function like this:

1$dateString1 = '2022-05-01';
2$dateString2 = '2022-05-01 10:30:00';
3$format1 = 'Y-m-d';
4$format2 = 'Y-m-d H:i:s';
5
6if (isDateTime($dateString1, $format1)) {
7    echo "$dateString1 is a valid date format.";
8} else {
9    echo "$dateString1 is not a valid date format.";
10}
11
12if (isDateTime($dateString2, $format2)) {
13    echo "$dateString2 is a valid datetime format.";
14} else {
15    echo "$dateString2 is not a valid datetime format.";
16}

This code will output:

2022-05-01 is a valid date format.
2022-05-01 10:30:00 is a valid datetime format.

That's it! Small and cringe... :smile:

A PHP demo/repos link

No response

PayPal Link for Donation (PHP Storyteller)

No response

Share This Story