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.
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.
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; } ?> |
1 2 3 4 |
// Returns false var_dump(validateDate('2015-15-01')); var_dump(validateDate('2012-14-03')); var_dump(validateDate('2019-5-25')); |
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..!
3 Replies to “How to Validate Date String in PHP”