How to Check If A String Is A Date in PHP
Posted on: March 01, 2021 by Ariessa Norramli
In this article, you will learn how to check if a string is a date or not in PHP.
Let’s say you have 2 string variables.
// A string variable named 'a' with value "2021-03-01"
$a = "2021-03-01";
// A string variable named 'b' with value "2021-13-01"
$b = "2021-13-01";
Check If A String Is A Date
In order to check if a string is a date or not, you can use the strtotime()
method.
// A string variable named 'a' with value "2021-03-01"
$a = "2021-03-01";
// A string variable named 'b' with value "2021-13-01"
$b = "2021-13-01";
// This function checks if a string is a valid date or not
function checkString($string) {
// If the string can be converted to UNIX timestamp
if (strtotime($string)) {
// Display valid date message
echo "The string $string is a valid date. <br/>" ;
}
// Else if the string cannot be converted to UNIX timestamp
else {
// Display not valid date message
echo "The string $string is not a valid date. <br/>";
}
}
checkString($a);
checkString($b);
Note: The strtotime()
method functions by parsing an English datetime string into a UNIX timestamp.
Share on social media
//