Skip to content

Instantly share code, notes, and snippets.

@gRegorLove
Last active January 5, 2016 02:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gRegorLove/97a705c920022e2a8b3c to your computer and use it in GitHub Desktop.
Save gRegorLove/97a705c920022e2a8b3c to your computer and use it in GitHub Desktop.
PHP date validation with DateTime
<?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