This content originally appeared on CodeSource.io and was authored 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.
The post How to Check If A String Is A Date in PHP appeared first on CodeSource.io.
This content originally appeared on CodeSource.io and was authored by Ariessa Norramli
![](https://www.radiofree.org/wp-content/plugins/print-app/icon.jpg)
Ariessa Norramli | Sciencx (2021-03-01T12:32:57+00:00) How to Check If A String Is A Date in PHP. Retrieved from https://www.scien.cx/2021/03/01/how-to-check-if-a-string-is-a-date-in-php/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.