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

PHP中使用strtotime转换日期时间为时间戳失败求助

解决strtotime解析"18 May 2.50pm"返回空值的问题

嘿,我完全懂这种卡壳的感觉——strtotime对这种带小数点的时间格式确实不太兼容!

问题出在strtotime的默认解析规则上:它只认冒号分隔的时分格式(比如2:50pm),而你写的2.50pm里的小数点会让它摸不着头脑,自然就返回空值了。

给你几个实用的解决方案:

  • 方案一:简单替换小数点为冒号
    先预处理字符串,把小数点换成冒号,再传给strtotime:

    $originalDate = "18 May 2.50pm";
    $fixedDate = str_replace('.', ':', $originalDate);
    echo strtotime($fixedDate); // 现在就能输出正确的时间戳啦
    
  • 方案二:用DateTime类(更推荐!)
    DateTime类的格式解析能力比strtotime灵活得多,哪怕先做替换再指定格式解析,稳定性更高:

    $originalDate = "18 May 2.50pm";
    $fixedDate = str_replace('.', ':', $originalDate);
    $dateObj = DateTime::createFromFormat('d M g:ia', $fixedDate);
    
    if ($dateObj) {
        echo $dateObj->getTimestamp();
    } else {
        echo "日期格式解析失败,请检查输入";
    }
    
  • 方案三:正则处理更复杂的情况
    如果你的时间格式偶尔有变体(比如10.30am、3.05pm),用正则替换更稳妥:

    $originalDate = "18 May 2.50pm";
    $fixedDate = preg_replace('/(\d+)\.(\d+)([ap]m)/i', '$1:$2$3', $originalDate);
    echo strtotime($fixedDate);
    

总的来说,DateTime类在处理非标准日期格式时容错性更强,建议日常开发优先用它,能少踩很多解析的坑~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:38:47