Chris
Chris

Reputation: 3846

PHP exception handling on DateTime object

Does anybody know why this function, when passed an invalid date (e.g. timestamp) to it, still throws an error despite the try-catch?

function getAge($date){
    try {
        $dobObject = new DateTime($date);
        $nowObject = new DateTime();

        $diff = $dobObject->diff($nowObject);
    }

    catch (Exception $e) {
        echo 'Error: ',  $e->getMessage();
    }

    return $diff->y;
}

Error:

Fatal error: Uncaught exception 'Exception' with message 'DateTime::_construct() [datetime.--construct]: Failed to parse time string (422926860) at position 7 (6): Unexpected character' in ... .php:4 Stack trace: #0 ... .php(4): DateTime->_construct('422926860') #1 ... .php(424): getAge('422926860') #2 {main} thrown in/... .php on line 4

Thank you very much in advance!

Upvotes: 3

Views: 4335

Answers (1)

Nemanja
Nemanja

Reputation: 1535

Chris, you cannot catch fatal errors, at very least you shouldn't.

Quoting keparo:

PHP won't provide you with any conventional means for catching fatal errors because they really shouldn't be caught. That is to say, you should not attempt to recover from a fatal error. String matching an output buffer is definitely ill-advised.

If you simply have no other way, take a look at this post for more info and possible how-tos.

Try this:

function isDateValid($str) {

  if (!is_string($str)) {
     return false;
  }

  $stamp = strtotime($str); 

  if (!is_numeric($stamp)) {
     return false; 
  }

  if ( checkdate(date('m', $stamp), date('d', $stamp), date('Y', $stamp)) ) { 
     return true; 
  } 
  return false; 
} 

And then :

 if isDateValid( $yourString ) {
    $date = new DateTime($yourString);
 }

Upvotes: 6

Related Questions