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

PHP日期格式转换异常:返回01-01-1970或报错求助

问题原因与解决方法

1. strtotime 返回1970日期的原因

strtotime() 对横杠分隔的日期格式解析逻辑是优先识别为 d-m-Y(日-月-年)或 Y-m-d(年-月-日),你的输入 04-13-2023 被它误判为日-月-年格式,其中13作为月份是无效值,导致strtotime()返回false。而date()函数处理false时,会默认使用Unix时间戳0对应的日期,也就是01-01-1970。

2. date_create_from_format 报错的原因

date_create_from_format() 返回的是DateTime对象,不是字符串,直接和字符串拼接输出会触发类型转换错误,必须调用format()方法生成指定格式的字符串才能正常输出。

正确的转换代码

$dispatch_date = "04-13-2023";
print_r("dispatch_date: " . $dispatch_date);

// 方法一:用date_create_from_format配合format
$newDate2 = date_create_from_format('m-d-Y', $dispatch_date);
if ($newDate2) { // 先验证日期是否有效
    $formattedDate = $newDate2->format('d-m-Y');
    print_r("date2: " . $formattedDate);
} else {
    print_r("输入日期无效");
}

// 方法二:用DateTime类的静态方法createFromFormat
$dateObj = DateTime::createFromFormat('m-d-Y', $dispatch_date);
if ($dateObj) {
    $formattedDate = $dateObj->format('d-m-Y');
    print_r("date: " . $formattedDate);
}
exit;

预期输出

dispatch_date: 04-13-2023
date2: 13-04-2023
date: 13-04-2023

建议始终添加日期有效性验证,避免因输入非法日期导致后续逻辑出错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 18:22:42