
本文讲解如何将MySQL中查询出的日期字符串(如“2023-05-12 14:30:45”)安全转换为自定义格式(如“12/05/2023 14:30”),重点解决date_format()因传入字符串而非DateTime对象导致的警告问题。
本文讲解如何将mysql中查询出的日期字符串(如“2023-05-12 14:30:45”)安全转换为自定义格式(如“12/05/2023 14:30”),重点解决`date_format()`因传入字符串而非datetime对象导致的警告问题。
在使用MySQL + MySQLi原生扩展查询数据时,date_created字段通常以字符串形式返回(例如 '2024-07-15 09:22:36')。此时若直接调用 date_format($new['date_created'], 'd/m/Y H:i'),会触发以下错误:
Warning: date_format() expects parameter 1 to be DateTimeInterface, string given
这是因为 date_format() 是面向对象方法 DateTime::format() 的函数式别名,它要求第一个参数必须是 DateTime 或实现了 DateTimeInterface 的对象,而不能是原始字符串。
✅ 正确做法:先用 date_create() 将字符串解析为 DateTime 对象,再格式化:
foreach ($news as $new) {
$formattedDate = date_format(date_create($new['date_created']), 'd/m/Y H:i');
echo "<p>ID: {$new['id']}, 标题: {$new['title']}, 发布时间: {$formattedDate}</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill5233" title="btpanel phpsite 宝塔面板PHP网站"><img
src="https://img.php.cn/upload/skill/000/000/081/179040786932301.jpg" alt="btpanel phpsite 宝塔面板PHP网站" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill5233" title="btpanel phpsite 宝塔面板PHP网站" class="overflowclass">btpanel phpsite 宝塔面板PHP网站</a>
<p class="overflowclass">宝塔面板 PHP 网站管理:站点创建、删除、启停、PHP 版本切换、域名管理、SSL证书管理、伪静态管理、数据库管理</p>
</div>
<a rel="nofollow" href="/xiazai/skill5233" title="btpanel phpsite 宝塔面板PHP网站" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>";
}
⚠️ 注意事项:
-
date_create()在遇到非法日期字符串时会返回false,建议增加健壮性检查:$dateObj = date_create($new['date_created']); if ($dateObj === false) { $formattedDate = '无效日期'; } else { $formattedDate = $dateObj->format('d/m/Y H:i'); } - 更推荐使用面向对象写法(语义清晰、易链式调用):
$formattedDate = (new DateTime($new['date_created']))->format('d/m/Y H:i'); - 确保数据库中
date_created字段类型为DATETIME或TIMESTAMP,且值符合 ISO 8601 格式(如Y-m-d H:i:s),否则解析可能失败。
? 小结:PHP 的日期格式化不是“字符串处理”,而是“对象操作”。从数据库读取的日期始终需先实例化为 DateTime 对象,再调用 format() —— 这既是语法要求,也是保障时区、闰秒、本地化等特性的基础。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










