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

PHP:给定Unix时间戳,如何获取不含当前日期的后两天00:00时间?

PHP 获取指定日期后两天的00:00时间实现方案

你遇到的问题核心是原方法会保留原时间戳的时分秒,要得到目标日期的零点,需要先清零时分秒再计算天数,或者直接定位到目标日期的00:00,以下是几种可行的实现方式:

方法一:使用strtotime结合日期格式化

先提取原时间戳的日期部分,再拼接目标时间规则,让strtotime解析出零点时间:

$current_timestamp = 1660293621;
// 提取原日期后,拼接"+3天 00:00:00"规则
$target_time = strtotime(date('Y-m-d', $current_timestamp) . ' +3 days 00:00:00');
// 格式化输出结果
echo date('Y-m-d H:i:s', $target_time); // 输出:2022-08-15 00:00:00

方法二:使用DateTime类(推荐)

DateTime类的API更直观,可读性更强,适合处理复杂日期操作:

$current_timestamp = 1660293621;
// 从时间戳初始化DateTime对象
$date = DateTime::createFromFormat('U', $current_timestamp);
// 直接修改到目标日期的零点
$date->modify('midnight +3 days');
// 输出格式化后的时间
echo $date->format('Y-m-d H:i:s'); // 输出:2022-08-15 00:00:00

也可以分步操作,逻辑更清晰:

$current_timestamp = 1660293621;
$date = new DateTime();
$date->setTimestamp($current_timestamp);
// 先将时间设为当天零点,再加3天
$date->setTime(0, 0, 0)->modify('+3 days');
echo $date->format('Y-m-d H:i:s');

为什么原方法不符合预期?

strtotime("+3 Days", $current_date)是在原时间的基础上直接增加3天,会完整保留原时间戳的时分秒(8:40),所以无法得到零点时间。必须先将时分秒清零,再进行天数偏移,或者直接指定目标日期的零点规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:30:57