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

PHP获取「下一个每月首个周一」:strtotime异常问题及替代方案

PHP 获取「下一个每月首个周一」的正确实现

问题场景与原代码缺陷

为每月首个周一召开会议的非营利组织搭建网站时,需要编写PHP代码返回下一个每月首个周一的日期。最初使用的代码存在逻辑问题:

<?php echo date("d-M-Y", strtotime("next first monday of the month"));?>

该代码仅在当前日期晚于当月首个周一能正确返回下月首个周一,但如果当前日期早于当月首个周一,仍错误返回下月的日期,而非当月的首个周一。

解决方案

以下是两种可靠的实现方式,均能正确判断并返回下一次会议的日期:

方式1:基于时间戳的对比实现

<?php
// 获取当月首个周一的时间戳
$firstMondayThisMonth = strtotime("first monday of this month");
$currentTime = time();

// 根据当前日期与当月首个周一的先后关系,确定目标日期
$nextFirstMonday = $currentTime > $firstMondayThisMonth 
    ? strtotime("first monday of next month") 
    : $firstMondayThisMonth;

// 格式化输出日期
echo date("d-M-Y", $nextFirstMonday);
?>

方式2:使用DateTime类(面向对象风格)

<?php
$today = new DateTime();
$firstMondayThisMonth = (new DateTime())->modify('first monday of this month');

// 判断当前日期是否已过当月首个周一
if ($today > $firstMondayThisMonth) {
    $nextFirstMonday = (new DateTime())->modify('first monday of next month');
} else {
    $nextFirstMonday = $firstMondayThisMonth;
}

// 格式化输出
echo $nextFirstMonday->format('d-M-Y');
?>

核心逻辑说明

两种方法的核心逻辑一致:

  1. 先计算当月首个周一的日期
  2. 将当前日期与该日期对比:
    • 若当前日期已过当月首个周一,返回下月首个周一
    • 若当前日期早于或等于当月首个周一,返回当月首个周一

这样就能确保无论当前处于当月的哪个时间段,都能准确返回下一次会议的日期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 01:57:44