How to check for a failed DateTime in PHP?

2019-08-30 11:01发布

When the following gets bad data PHP aborts.

PHP Fatal error:  Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (980671) at position 4 (7): Unexpected character'

How can I catch this if the data is bad to take other action so the PHP problem doesn't fail?

$date = new DateTime($TRANSACTION_DATE_MMDDYY_raw);

2条回答
Luminary・发光体
2楼-- · 2019-08-30 11:15

As @Rob W already said, you gotta catch that exception.

But what could cause that exception is inaproppriate datetime format.

To solve this, you could do instead:

try {
  $dt = DateTime::createFromFormat("MMDDYY", $TRANSACTION_DATE_MMDDYY_raw) ;
} catch(Exception $e){
  echo "Something went wrong: {$e->getMessage()} " ;
}

More about it: http://www.php.net/manual/en/datetime.createfromformat.php

查看更多
倾城 Initia
3楼-- · 2019-08-30 11:18

Use try and catch

try {
  $date = new DateTime($date);
} catch(Exception $e) {
  echo "Invalid date... {$e->getMessage()}";
}
查看更多
登录 后发表回答