Check if a string represents a valid Date or Time with PHP

PHP DateTime class, available with PHP versions greater than 5.2 is very powerful.

As an example, it ts very easy to check if a string represents a valid date or time, using any format and any timezone.

A solution could be the following function:

function isValidDateTimeString($str_dt, $str_dateformat, $str_timezone) {
        $date = DateTime::createFromFormat($str_dateformat, $str_dt, new DateTimeZone($str_timezone));
        return ($date === false ? false : true);
}

The problem

It’s strange, but PHP DateTime::createFromFormat will accept a date like ‘2013-13-10’ (format ‘Y-m-d’ in this example). In this case It will return a date of January of next year (‘2014-01-10’). However, DateTime::getLastErrors() will contain a warning: ‘The parsed date was invalid’.

Here are some workarounds:

A better approach

A solution could be to check returned date to be equal with input date (after apply date format)

function isValidDateTimeString($str_dt, $str_dateformat, $str_timezone) {
        $date = DateTime::createFromFormat($str_dateformat, $str_dt, new DateTimeZone($str_timezone));
        return $date && $date->format($str_dateformat) == $str_dt;
}

Even better

Probably, the best solution is to check DateTime::getLastErrors() array, which must NOT contain warnings or errors:

<?php
/**
 * Check if a string is a valid date(time)
 *
 * DateTime::createFromFormat requires PHP >= 5.3
 *
 * @param string $str_dt
 * @param string $str_dateformat
 * @param string $str_timezone (If timezone is invalid, php will throw an exception)
 * @return bool
 */
function isValidDateTimeString($str_dt, $str_dateformat, $str_timezone) {
        $date = DateTime::createFromFormat($str_dateformat, $str_dt, new DateTimeZone($str_timezone));
        return $date && DateTime::getLastErrors()["warning_count"] == 0 && DateTime::getLastErrors()["error_count"] == 0;
}
?>

If timezone is invalid, php will throw an exception. You may catch the exception, or, if you prefer so, you can check if $str_timezone is valid timezone (and probaly throw an exception or trigger an error).

Tip

If you are running older PHP versions, it’s time to upgrade 🙂

References

From PHP manual