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

CI4中DateTime对象无法转字符串,Twilio API数据插MySQL失败求助

解决Twilio DateTime对象插入MySQL的类型转换问题

从Twilio对话参与者接口获取的数据中,dateCreated和dateUpdated是已实例化的DateTime对象,直接将其插入MySQL时会抛出「Object of class DateTime could not be converted to string」错误。尝试修改数据库字段类型为date、datetime、text或varchar均无效,另外尝试用new \DateTime($record->dateCreated)转换时,会触发「DateTime::__construct() expects parameter 1 to be string, object given」错误。

解决思路

直接调用DateTime对象的format()方法,将其转为MySQL支持的datetime格式字符串(如Y-m-d H:i:s),无需重复实例化DateTime对象。

修改后的代码示例

$sql=[
    "id_conversation"=>$conversation_id,
    "identity"=>$record->identity,
    "identity_proxy_address"=>$explode_whatsapp[1],
    "date_created"=>$record->dateCreated->format('Y-m-d H:i:s'),
    "date_updated"=>$record->dateUpdated->format('Y-m-d H:i:s'),
];
$builder->insert($sql);

说明

Twilio返回的dateCreated和dateUpdated本身就是DateTime实例,不需要再用new \DateTime()重新构造。调用format()方法生成符合MySQL要求的字符串格式后,将数据库对应字段类型设置为datetime(或timestamp)即可正常插入。

内容的提问来源于stack exchange,提问作者Luis Lara

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:45:34