Sling Academy
Home/PHP/PHP: Check if a string can be converted to date time

PHP: Check if a string can be converted to date time

Last updated: January 09, 2024

Introduction

Handling date and time is a common task in web development. PHP offers a multitude of functions to parse and format date strings. This tutorial provides a deep dive into various methods to check if a string is convertible to a date-time object in PHP.

Using strtotime() Function

The strtotime() function is one of the simplest ways to verify if a string is a valid date. It parses most English textual date descriptions into a Unix timestamp. If it fails, it returns false.

$string = '2022-08-25';
$timestamp = strtotime($string);
if ($timestamp !== false) {
    echo 'Valid Date: ' . date('Y-m-d', $timestamp);
} else {
    echo 'This string cannot be converted to a date.';
}

Remember that strtotime() supports many formats but not all, and it’s recommended to use standardized date formats like ISO 8601 for reliable results.

Using DateTime Class

The DateTime class provides an object-oriented interface to validate and manipulate date and time.

try {
    $date = new DateTime('2022-08-25');
    echo 'Valid Date: ' . $date->format('Y-m-d');
} catch (Exception $e) {
    echo 'This string cannot be converted to a date.';
}

The advantage of using the DateTime class is its exception handling, which can be used to cleanly catch any error resulting from an invalid date string.

Using date_create() Function

The date_create() function is an alias for the constructor of the DateTime class and can also be used to validate a date string.

$date = date_create('13-13-2022');
if ($date) {
    echo 'Valid Date: ' . date_format($date, 'Y-m-d');
} else {
    echo 'This string cannot be converted to a date.';
}

Note that invalid dates, like the 13th month, will result in false. It handles many formats and edge cases.

Using DateTime::createFromFormat

The DateTime::createFromFormat method allows checking for validity against a specific format.

$format = 'm/d/Y';
$string = '08/25/2022';
$date = DateTime::createFromFormat($format, $string);
if ($date && $date->format($format) === $string) {
    echo 'Valid Date: ' . $date->format('Y-m-d');
} else {
    echo 'This string does not match the expected format or is not a valid date.';
}

This method is especially useful when we expect dates to come in a certain format and others should be considered invalid.

Validating Complex or Arbitrary Formats

For intricate date string formats or when we need to include additional validation logic, we can combine the use of DateTime or DateTime::createFromFormat with regular expressions.

$pattern = '/^(?!
# all the regex and validation code

Regular expressions offer limitless possibilities to check for character sequences, thus ensuring date strings match exactly the desired format before attempting to convert them.

Conclusion

We explored several methods to verify if a string can be converted to a date in PHP. Understanding and choosing the right function or method depends on the specific application needs and the expected date format. Use these techniques to ensure robust date-time handling in your PHP applications.

Next Article: PHP: Remove Accent Marks from a String

Previous Article: PHP: Check if a string can be converted to a number

Series: Working with Numbers and Strings in PHP

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array