Check if String contains a Date in PHP

This tutorial will discuss how to check if string contains a date in PHP.

To check if a string contains a valid date in PHP, we will use the DateTime::createFromFormat() function. It accepts two parameters:

  • The first is a string containing the format of the date
  • The second is a string containing the actual date.

If the string with the date contains a valid date in the given format, this function will return a valid DateTime object. Otherwise, it will return false. We can then convert the DateTime object back into a string by calling the format() function on it. If the resulting string matches the given date string, it means the original string contains a valid date.

We have created a separate function for this,

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

It accepts the date in string format as the first argument and the format string as the second argument. The format string specifies the format of the date in the first parameter.

In the example below, we will use this function to check if two dates are valid or not.

Let’s see the complete example,

<?php
/**
 * Check if a string is a valid date.
 *
 * @param string $date The date string to validate.
 * @param string $format The expected date format.
 * @return bool True if the string is a valid date, false otherwise.
 */
function isValidDate($date, $format = 'Y-m-d')
{
    $dateTime = DateTime::createFromFormat($format, $date);
    return $dateTime && $dateTime->format($format) === $date;
}

$dateString = '2023-06-19';

if (isValidDate($dateString)) {
    echo "$dateString is a valid date. n";
} else {
    echo "$dateString is not a valid date. n";
}

$dateString = '19/06/2023';

if (isValidDate($dateString, 'd/m/Y')) {
    echo "$dateString is a valid date. n";
} else {
    echo "$dateString is not a valid date. n";
}
?>

Output

2023-06-19 is a valid date. 
19/06/2023 is a valid date.

Summary

Today, we learned how to check if string contains a 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