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

PHP中midnight无法实现时间截断?DateTime时间设置异常咨询

PHP DateTime 常见问题排查与解决

问题1:first day of -1 month midnight 无法设置时间为午夜

执行以下代码时,即使添加了midnight,结果仍和未添加时一致,无法将时间设置为午夜(已在PHP 7.3.33、PHP 8.2.4版本验证):

new DateTime('first day of -1 month midnight');

这是PHP DateTime相对时间解析顺序导致的问题:first day of -1 month会先定位到上个月的第一天,但后续的midnight并未正确覆盖时间部分。

解决方法:

  • 调整相对时间顺序,优先指定时间再定位日期:
    new DateTime('midnight first day of -1 month');
    
  • 或者先获取目标日期,再强制设置午夜时间:
    $date = new DateTime('first day of -1 month');
    $date->setTime(0, 0, 0);
    

问题2:yesterday noon 格式化后分钟不为零

执行以下代码时,无法输出noon对应的正确时间,分钟字段不为零:

echo (new DateTime('yesterday noon'))->format('Y-m-d h:m');

核心原因是格式化字符串使用了错误的占位符:m代表月份,而表示分钟的正确占位符是i。

修正后的代码:

echo (new DateTime('yesterday noon'))->format('Y-m-d h:i');

补充说明:

  • h是12小时制格式,正午(noon)会显示为12;H是24小时制格式,正午同样显示为12。
  • 午夜在h格式下显示12,在H格式下显示00。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 15:54:54