You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter从日期获取周数时报DateTime无法转字符串错误如何解决

错误原因

你代码第一行使用了PHP短输出标签<?=,该标签等价于<?php echo ,执行$deliverydate = new DateTime($order->delivery_date)赋值操作时,PHP会自动输出赋值表达式的返回值(即DateTime对象本身),而DateTime对象没有默认的字符串转换逻辑,因此抛出了该错误。
另外你第二行的<?php $week?>仅声明了变量,没有添加输出逻辑,即使解决了报错也无法正常显示周数。

修复方案

将赋值逻辑移到普通PHP标签中,输出周数时再用短输出标签即可,参考代码如下:

<?php
$deliverydate = new DateTime($order->delivery_date);
$week = $deliverydate->format("W");
?>
<?= $week ?>

可选优化

如果$order->delivery_date可能为空或存在格式非法的场景,可添加校验逻辑避免初始化DateTime时报错:

<?php
$week = '';
if (!empty($order->delivery_date) && strtotime($order->delivery_date)) {
    $deliverydate = new DateTime($order->delivery_date);
    $week = $deliverydate->format("W");
}
?>
<?= $week ?>

内容的提问来源于stack exchange,提问作者Bert Swinnen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 23:15:00