Function to check if a string is a date

Function to check if a string is a date

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Regex Patterns vs. PHP Built-ins for Date Validation

Validating input against a specific format is a common requirement in application logic, but relying solely on regular expressions to verify semantic correctness often leads to subtle bugs. Consider a string matching XXXX-XX-XX XX:XX:XX. A naive regex like /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/ will successfully match impossible dates such as February 30th or December 32nd. While this pattern confirms the format, it does not confirm validity.

If your goal is strictly to ensure the string adheres to the visual structure XXXX-XX-XX XX:XX:XX without worrying about calendar logic, a regex is acceptable. However, if you need to determine whether that date actually exists in time, you must move beyond pattern matching into semantic validation. PHP provides robust tools for this exact scenario, specifically within the DateTime class and its factory methods.

The Regex Approach: Format Only

If you strictly require a regular expression because you are operating outside of an object-oriented context or need the highest possible performance on massive streams of data where object creation overhead is prohibitive, here is how to construct the pattern for your specific requirements.

To match four digits for the year, two for the month, and so on, separated by hyphens and a space before the time components, you can use:

$pattern = '/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/';

This expression enforces the structure. It ensures there are exactly four digits at the start, followed by two-digit groups separated by hyphens or a space-colon combination at the end. The anchors ^ and $ are critical here; without them, the regex might match a substring within a larger string like 2012-06-14 01:46:28 extra.

While this works for format checking, remember that it will return true for 2023-13-45 99:99:99. If your use case demands that the string represents a real moment in time, this approach is insufficient.

Leveraging DateTime::createFromFormat

PHP’s DateTime::createFromFormat is the standard solution when you need to validate both format and calendar logic. This method attempts to parse a date based on a specific format string. If the input does not match the format or represents an impossible date, it returns false.

Here is how you can implement this check:

$format = 'Y-m-d H:i:s';
$dateString = '2012-06-14 01:46:28';

$date = DateTime::createFromFormat($format, $dateString);

if ($date && $date instanceof DateTime) {
    echo "Valid date.";
} else {
    echo "Invalid date or format.";
}

This approach is generally preferred because it handles edge cases automatically. For instance, 2012-02-30 will fail validation even though the regex matches it perfectly. The DateTime class internally checks for leap years and correct day counts for each month.

Performance Considerations

There is a trade-off between using regex and DateTime::createFromFormat. Creating a DateTime object involves more overhead than running a simple regex match. If you are validating millions of rows in a high-frequency trading system or processing a massive log file, the regex approach might be necessary to avoid memory allocation spikes.

However, if you are building a web application where correctness is paramount, the slight performance cost of DateTime is negligible and well worth avoiding logic errors. A function that claims to validate dates but accepts February 29th in a non-leap year introduces data integrity issues that are far more expensive to fix later than the initial microsecond delay in parsing.

When to Use Laravel's Helpers

If you are working within the Laravel ecosystem, you might wonder if there is a cleaner way to handle this without writing raw PHP logic. While Laravel doesn't expose a dedicated isValidDate() helper for arbitrary strings out of the box, it encourages using the underlying DateTime facade or casting strings directly if you trust the input format.

For more complex validation scenarios within Laravel forms, you would typically define a custom rule that wraps this logic. This keeps your validation file clean and reusable:

Validator::make($request->all(), [
    'date_field' => ['required', 'date:Y-m-d H:i:s']
]);

Laravel's built-in date validation rule handles format checking, but like the PHP native approach, it relies on internal date parsing to ensure semantic validity. If you need custom logic for specific edge cases or non-standard timezones, wrapping the DateTime::createFromFormat method in a custom validator rule remains the most robust pattern.

Ultimately, choose your tool based on whether you need format-only matching or full semantic validation. For real-world applications, the overhead of using DateTime is usually an acceptable price for correctness.

Our network