Last active
January 5, 2016 02:21
-
-
Save gRegorLove/97a705c920022e2a8b3c to your computer and use it in GitHub Desktop.
PHP date validation with DateTime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Validates a date string and converts it to a DateTime object | |
* Returns DateTime object on success, bool false on failure | |
* @param string $date | |
* @return DateTime|bool | |
*/ | |
function validate_date($date) | |
{ | |
try | |
{ | |
$dt = new DateTime($date); | |
$temp_errors = DateTime::getLastErrors(); | |
# Ensures date errors like '2016-02-30' are also caught | |
if ( !empty($temp_errors['warning_count']) ) | |
{ | |
throw new Exception(); | |
} | |
return $dt; | |
} | |
catch ( Exception $e ) | |
{ | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment