如何在PHP中检查失败的DateTime


How to check for a failed DateTime in PHP?

当以下内容得到错误数据时,PHP将中止。

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

如果数据不好,我该如何捕捉到这一点,以便采取其他操作,从而使PHP问题不会失败?

$date = new DateTime($TRANSACTION_DATE_MMDDYY_raw);

使用trycatch

try {
  $date = new DateTime($date);
} catch(Exception $e) {
  echo "Invalid date... {$e->getMessage()}";
}

正如@Rob W已经说过的,您必须捕获该异常。

但可能导致这种异常的原因是日期时间格式不合适。

为了解决这个问题,你可以改为:

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

更多信息:http://www.php.net/manual/en/datetime.createfromformat.php