Check if given string is a valid date in PHP
This article demonstrates how to check if a given string is a valid date in PHP.
1. Using strtotime() function
You can determine if a string is a valid date using the strtotime() function. It returns the timestamp on success and false otherwise. It should be noted that the function doesn’t accept any custom date format but instead expects a string containing an English date format.
|
1 2 3 4 5 6 7 8 9 |
<?php function validateDate($date) { return strtotime($date) !== false; } $date = '2017/10/31'; var_dump(validateDate($date)); ?> |
2. Using DateTime::format() function
If your date string contains a non-standard format, you can use the createFromFormat() function from the DateTime class to parse the strings. Then invoke the DateTime::format() function to determine if the date is formatted according to the given format. The following code example shows invocation of this function:
|
1 2 3 4 5 6 7 8 9 10 |
<?php function validateDate($date, $format) { $dateTime = DateTime::createFromFormat($format, $date); return $dateTime && $dateTime->format($format) === $date; } $date = '2017/10/31'; var_dump(validateDate($date, 'Y/m/d')); ?> |
If you prefer the procedural style over the object-oriented style, you can use the date_create_from_format() and date_format() functions. These functions are the aliases of the DateTime::createFromFormat() and DateTime::format() functions, respectively.
|
1 2 3 4 5 6 7 8 9 10 |
<?php function validateDate($date, $format) { $dateTime = date_create_from_format($format, $date); return $dateTime && date_format($dateTime, $format) === $date; } $date = '2017/10/31'; var_dump(validateDate($date, 'Y/m/d')); ?> |
That’s all there is to checking if a given string is a valid date in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)