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

PHP使用DateTime类获取距离指定日期更近的下一个周一或周三的方法

核心结论

PHP 的 DateTime::modify() 方法不支持直接传入多个工作日选项自动匹配更近的日期,你可以通过分别计算两个目标日期后取更早值的方案实现需求。

实现代码
$date = 20211002;
$baseDate = DateTime::createFromFormat('Ymd', $date);

// 克隆基础日期对象,避免modify操作修改原对象导致计算偏差
$nextMonday = clone $baseDate;
$nextMonday->modify('next monday');
$nextWednesday = clone $baseDate;
$nextWednesday->modify('next wednesday');

// 比较两个日期取更早的即为目标结果
$targetDate = min($nextMonday, $nextWednesday);

// 按要求格式输出
echo $targetDate->format('d/m/Y');
补充说明

如果你需要把「当天就是周一/周三」的情况也纳入符合要求的结果,把next替换为this即可,比如modify('this monday'),这样输入日期当天为目标工作日时会直接返回当天,不会跳到下一周的对应日期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:27:01