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

如何使用PHP获取当前月份的最后一个工作日(周一至周五)

PHP获取当月最后一个工作日(周一至周五)实现方案

核心逻辑

  • 先定位到目标月份的最后一天
  • 从最后一天倒序排查,直到找到第一个属于周一到周五的日期,即为所求的最后一个工作日

代码实现

最简实现(默认取当前月份)

function getCurrentMonthLastWorkday(): string
{
    // 初始化当月最后一天的日期对象
    $date = new DateTime('last day of this month');

    // N格式返回1~7,1为周一、5为周五、6为周六、7为周日,周末就往前减1天
    while ($date->format('N') >= 6) {
        $date->modify('-1 day');
    }

    return $date->format('Y-m-d');
}

// 调用测试
echo getCurrentMonthLastWorkday();

支持指定年月的通用实现

function getSpecifiedMonthLastWorkday(int $year, int $month): string
{
    // 参数合法性校验
    if ($year < 1970 || $month < 1 || $month > 12) {
        throw new InvalidArgumentException('请传入合法的年份和月份参数');
    }

    $date = DateTime::createFromFormat('Y-n', sprintf('%d-%d', $year, $month));
    $date->modify('last day of this month');

    while ($date->format('N') >= 6) {
        $date->modify('-1 day');
    }

    return $date->format('Y-m-d');
}

// 调用测试:获取2024年10月的最后一个工作日
echo getSpecifiedMonthLastWorkday(2024, 10);

注意事项

  • 本方案仅按照周一到周五的规则判断工作日,不包含法定节假日调休、补班的场景,如果需要适配该场景,需要额外维护官方发布的年度节假日数据表做二次校验。
  • 代码依赖PHP 5.2及以上版本,使用PHP内置的DateTime系列类实现,无需安装额外扩展。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:15:02