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

PHP动态生成未来12个月间隔15天的日期范围下拉选项

修正PHP动态生成交替日期范围下拉选项的方案

需求说明

需要生成覆盖未来12个月的下拉选项,日期范围按以下规则交替:

  • 偶数位选项(第1、3、5...个):当月1日至当月月末
  • 奇数位选项(第2、4、6...个):当月15日至下月15日

修正后的完整代码

<?php
$dateOptions = [];
// 循环生成未来12个月的日期选项
for ($i = 0; $i < 12; $i++) {
    $baseDate = (new DateTime())->modify("+$i months");
    $year = $baseDate->format('Y');
    $month = $baseDate->format('m');

    // 根据循环索引奇偶性切换日期范围类型
    if ($i % 2 === 0) {
        // 1日至当月月末
        $start = "$year-$month-01";
        $end = $baseDate->format('Y-m-t');
        $label = "{$baseDate->format('F Y')} 1日至月末";
    } else {
        // 当月15日至下月15日
        $start = "$year-$month-15";
        $nextMonth = (new DateTime($start))->modify('+1 month');
        $end = $nextMonth->format('Y-m-15');
        $label = "{$baseDate->format('F Y')} 15日至{$nextMonth->format('F Y')} 15日";
    }

    $dateOptions[] = [
        'label' => $label,
        'value' => "$start|$end"
    ];
}
?>

<!-- 渲染下拉菜单 -->
<select name="date_range">
    <?php foreach ($dateOptions as $opt): ?>
        <option value="<?= htmlspecialchars($opt['value']) ?>">
            <?= htmlspecialchars($opt['label']) ?>
        </option>
    <?php endforeach; ?>
</select>

关键实现说明

  1. 日期处理准确性:依赖PHP的DateTime类处理日期计算,自动适配闰年、不同月份天数等特殊情况,避免手动计算错误。
  2. 交替逻辑控制:通过循环索引$i的奇偶判断($i % 2 === 0),实现两种日期范围的交替生成。
  3. 月末日期获取:使用format('t')直接获取当月最后一天,无需手动计算当月天数。
  4. 安全输出:用htmlspecialchars转义选项内容,避免XSS攻击风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:33:22