我正在尝试从数据库表中获取created_at
字段,但它抛出以下错误:
内部存储的日期/时间/时间戳值无法转换为 DateTime:'
Cook
'[包装:DateTime :: __ construct():失败 解析位置0(<)上的时间字符串(Cook
):意外 字符]
获取日期的代码:
foreach ($pager->getResults() as $row):
?>
<tr>
<td><?php echo $row->getTitle() ?></td>
<td><?php echo ($row->getStatus()) ? 'Active' : 'Inactive' ?></td>
<td><?php echo date(sfConfig::get('app_display_alternate_format_for_date'), strtotime($row->getCreatedAt())) ?></td>
<td>
</td>
</tr>
配置日期:
'app_display_alternate_format_for_date'=>'M-d-Y'
以数据库格式保存的日期:
2017-09-15 08:08:02
BaseModel的Base getCreatedAt函数:
public function getCreatedAt($format = 'Y-m-d H:i:s')
{
if ($this->created_at === null) {
return null;
}
if ($this->created_at === '0000-00-00 00:00:00') {
// while technically this is not a default value of NULL,
// this seems to be closest in meaning.
return null;
} else {
try {
$dt = new DateTime($this->created_at);
} catch (Exception $x) {
throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->created_at, true), $x);
}
}
if ($format === null) {
// Because propel.useDateTimeClass is TRUE, we return a DateTime object.
return $dt;
} elseif (strpos($format, '%') !== false) {
return strftime($format, $dt->format('U'));
} else {
return $dt->format($format);
}
}
答案 0 :(得分:1)
首先,异常看起来像在字段中找到了字符串Cook
。
我想在var_dump($this->created_at);exit;
之前一行new DateTime($this->created_at)
排除这种可能性。
一旦确定情况并非如此,请尝试给出字符串的格式。代替new DateTime()
使用:
$dt = date_create_from_format('Y-m-d H:i:s', $this->created_at);
或者更好:
$dt = date_create_from_format($format, $this->created_at);