Hello Everyone hopes you all are doing well and today we talk about How to Validate Date String in PHP. Validation of date or an input string is a valid date or not. By using DateTime class you can check an input string is valid or not. From some example, we will show you how to validate the string on server-side input using PHP.
In This Article
Complete explanation on How to Validate Date String in PHP
The validateDate() function checks whether the given string is a valid date or not using PHP. It uses PHP DateTime class and createFromFormat() function which is an object-oriented method.
On the given OOP PHP function, checks string is a valid date or not and returns with boolean True OR False.
1 2 3 4 5 6 |
<?php function validateDate($date, $format = 'Y-m-d'){ $b = DateTime::createFromFormat($format, $date); return $b && $b->format($format) === $date; } ?> |
Now we call the validateDate() function and through passing the date string in the first parameter.
1 2 3 4 |
// Returns false var_dump(validateDate('2015-15-01')); var_dump(validateDate('2012-14-03')); var_dump(validateDate('2019-5-25')); |
Above code, all are return false because of our validation on the function.
1 2 3 |
// Returns true var_dump(validateDate('2015-12-02')); var_dump(validateDate('1980-10-18')); |
On the above PHP function, we use createFromFormat(), which is an Object-oriented style code.
(adsbygoogle = window.adsbygoogle || []).push({});
Example- DateTime::createFromFormat()
Object oriented style
1 2 3 |
$date = DateTime::createFromFormat('j-M-Y', '15-Jan-2009'); echo $date->format('Y-m-d'); O/P: 2009-01-15 |
Procedural style
1 2 3 |
$date = date_create_from_format('j-M-Y', '15-Jan-2009'); echo date_format($date, 'Y-m-d'); O/P: 2009-01-15 |
Also check: Google Sheet Integration with WordPress without Plugin
Happy Coding..!
Was this article helpful?
YesNo
Pingback: DATE PHP | PHP date() Function - PHPCODER.TECH
Pingback: How to Set PHP Variable in JavaScript With Example - PHPCODER.TECH