Check if String is a Valid Date in PHP

This tutorial will discuss about a unique way to check if string is a date in php.

Suppose we have a string containing a date
Now we want to verify that the string contains a valid date or not. For this, we are going to use the date format, which specifies that in which format string contains the date. Like in our case date in string and its format will be like this,

$strValue = "2023-06-05";
$dateFormat = "Y-m-d";

Now we can create a datetime object from the string and the format using the create DateTime::createFromFormat() function. After that we need to check that if the datetime object is not null and then we will convert this datetime object to string again and match it with the given string. If it matches, then it means that the given string contains a valid date.

We have created a separate function for this,

function isDateString($str, $format)
{
    $dateTime = DateTime::createFromFormat($format, $str);
    return $dateTime && $dateTime->format($format) === $str;
}

It accepts a string and a format in which string stores the date. It returns true if the given string contains a valid date in the given format.

Let’s see the complete example,

<?php
/**
 * Checks if a string represents a valid date
 * using DateTime::createFromFormat().
 *
 * @param string $str The string to check.
 * @param string $format The expected format of the date.
 * @return bool True if the string represents a valid date, false otherwise.
 */
function isDateString($str, $format)
{
    $dateTime = DateTime::createFromFormat($format, $str);
    return $dateTime && $dateTime->format($format) === $str;
}

// Example usage:
$strValue = "2023-06-05";
$dateFormat = "Y-m-d";

// Check fi string contains a valid date
if (isDateString($strValue, $dateFormat)) {
    echo "The string represents a valid date.";
} else {
    echo "The string does not represent a valid date.";
}
?>

Output

The string represents a valid date.

Summary

We learned how to check if a string contains a valid date in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top