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

PHP strtotime废弃问题:DateTime类替代实现报错求助

问题修复:用DateTime替代strtotime的错误修正

原代码逻辑是计算当前时间戳与CreationDate对应时间戳的秒数差值,但你修改后的代码存在类型错误:

  • time()返回整数类型的当前时间戳
  • $dateTime->format("Y-m-d")返回字符串类型的日期(如"2024-05-20")

字符串和整数直接相减会触发类型转换错误,导致代码报错。

正确修改方式(保持原逻辑)

直接使用DateTime类的getTimestamp()方法获取对应时间戳,和原逻辑完全一致:

$dateTime = new DateTime($r["CreationDate"]);
$lastUpdate = time() - $dateTime->getTimestamp();

更灵活的面向对象写法

如果需要获取天、小时、分钟等多单位的时间差,可使用diff()方法:

$dateTime = new DateTime($r["CreationDate"]);
$now = new DateTime();
$timeDiff = $now->diff($dateTime);

// 计算总秒数差值
$lastUpdate = $timeDiff->s + $timeDiff->i * 60 + $timeDiff->h * 3600 + $timeDiff->d * 86400;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 12:33:11