Although this has an accepted answer, it is not going to effectively work in all cases. For example, I test date validation on a form field I have using the date "10/38/2013", and I got a valid DateObject returned, but the date was what PHP call "overflowed", so that "10/38/2013" becomes "11/07/2013". Makes sense, but should we just accept the reformed date, or force users to input the correct date? For those of us who are form validation nazis, We can use this dirty fix: https://stackoverflow.com/a/10120725/486863 and just return false when the object throws this warning.
The other workaround would be to match the string date to the formatted one, and compare the two for equal value. This seems just as messy. Oh well. Such is the nature of PHP dev.
$d = DateTime::createFromFormat($format, $date);
// The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
if($d && $d->format($format) === $date) {
//it's a proper date!
}
else {
//it's not a proper date
}
When I work with unconventional APIs, I sometimes get a bit of a messy return instead of a well defined date format. So I use a rather inelegant class and I readily admit that it is brutal and unconventional in principle but it does me good sometimes ^^.