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

PHP有条件加减月份计算日期 解决非法月份值问题

解决方法

PHP 内置的日期处理类/函数已经自带了合法的月份偏移逻辑,不需要手动做年月的溢出判断,推荐用 DateTime 类实现:

// 初始化当前日期对象
$now = new DateTime();

if ($request->flagMonth == -1) {
    // 偏移到上一个月,自动处理跨年逻辑
    $now->sub(new DateInterval('P1M'));
    $query->where(
        ['month', '=', $now->format('n')],
        ['year', '>=', $now->format('Y')]
    );
} elseif ($request->flagMonth == 0) {
    $query->where(
        ['month', '=', $now->format('n')],
        ['year', '=', $now->format('Y')]
    );
} elseif ($request->flagMonth == 1) {
    // 偏移到下一个月,自动处理跨年逻辑
    $now->add(new DateInterval('P1M'));
    $query->where(
        ['month', '=', $now->format('n')],
        ['year', '>=', $now->format('Y')]
    );
}

补充说明

  • DateTime::format('n') 返回的是不带前导零的1-12范围的月份值,和你之前用 idate('m') 得到的输出格式完全一致,不需要修改现有数据库查询的匹配逻辑
  • 月份偏移会自动处理边界场景:1月减1个月自动转为上一年12月,12月加1个月自动转为下一年1月,不会再出现0、13这类非法取值
    如果更习惯用函数式写法,也可以用 strtotime 实现同等效果,示例如下:
// 示例:获取上一个月的月份和年份
$prevMonthTs = strtotime('-1 month');
$prevMonth = idate('m', $prevMonthTs);
$prevYear = idate('Y', $prevMonthTs);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:36:04