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

Laravel中如何使用Carbon Period获取指定年月的完整日期数组

动态生成指定年月的完整日期数组(1号到月末)

你可以借助Carbon的日期解析能力,封装一个支持动态传入年份、月份数字或月份名称的方法,快速生成指定年月的日期范围数组。

核心实现代码

use Carbon\Carbon;
use Carbon\CarbonPeriod;

/**
 * 生成指定年月从1号到月末的日期数组
 * @param int|string $year 目标年份(如2024)
 * @param int|string $month 目标月份(支持数字、英文全称/缩写,如1、'January'、'Jan')
 * @return array
 */
public function getMonthDateRange($year, $month)
{
    // 解析并生成当月第一天的日期实例
    $startDate = Carbon::parse("{$year}-{$month}-01")->startOfMonth();
    // 获取当月最后一天的日期实例
    $endDate = $startDate->copy()->endOfMonth();
    
    // 生成日期范围并转为数组
    return CarbonPeriod::create($startDate, $endDate)->toArray();
}

调用示例

1. 传入年份+月份数字

// 生成2024年2月的日期数组
$this->dateRange = $this->getMonthDateRange(2024, 2);
dd($this->dateRange);

输出结果会包含2024-02-01到2024-02-29的所有日期。

2. 传入年份+月份英文名称(全称/缩写)

// 生成2024年3月的日期数组(全称)
$this->dateRange = $this->getMonthDateRange(2024, 'March');
// 或者用缩写
$this->dateRange = $this->getMonthDateRange(2024, 'Mar');
dd($this->dateRange);

输出结果会包含2024-03-01到2024-03-31的所有日期。

补充说明

  • Carbon的parse方法自动兼容多种月份格式,无需额外处理月份名称和数字的转换
  • startOfMonth()和endOfMonth()方法会自动处理当月的第一天和最后一天,无需手动判断当月天数
  • 如果需要自定义日期格式(比如示例中的dd-mm-YYYY),可以遍历数组格式化:
$formattedDates = array_map(function($date) {
    return $date->format('d-m-Y');
}, $this->dateRange);
dd($formattedDates);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 05:42:17