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

Laravel中如何通过CarbonPeriod生成带序数的周文本格式标签

How to Generate Ordinal Week Labels like "Jan 1st week 2021" with CarbonPeriod

Got it, let's tweak your existing code to generate those ordinal week labels you're after. Here's a straightforward solution that fits right into your current loop:

Modified Code

$carbonPeriod = CarbonPeriod::create($startDate, '1 week', $endDate);

// Helper function to generate ordinal suffixes (st, nd, rd, th)
function getOrdinalSuffix($number) {
    // Handle special cases for 11-13
    if ($number >= 11 && $number <= 13) {
        return 'th';
    }
    // Match last digit to suffix
    switch ($number % 10) {
        case 1: return 'st';
        case 2: return 'nd';
        case 3: return 'rd';
        default: return 'th';
    }
}

foreach ($carbonPeriod as $period) {
    $startPeriod = clone $period;
    $endPeriod = clone $period;
    $startRange = $parsedStartDate->gt($startPeriod->startOfWeek()) ? $startDate : $startPeriod->startOfWeek()->format('Y-m-d');
    $endRange = $parsedEndDate->lt($endPeriod->endOfWeek()) ? $endDate : $endPeriod->endOfWeek()->format('Y-m-d');
    
    // Get the week number within the current month
    $weekOfMonth = $period->weekOfMonth();
    // Get the ordinal suffix for the week number
    $ordinalSuffix = getOrdinalSuffix($weekOfMonth);
    // Build the final label string
    $labels[] = sprintf('%s %d%s week %d', 
        $period->format('M'), // Short month name (Jan, Feb, etc.)
        $weekOfMonth,
        $ordinalSuffix,
        $period->year // Full year (2021, 2022, etc.)
    );
}

Breakdown of Changes

  1. Ordinal Suffix Helper Function
    Carbon doesn't have a built-in method to generate ordinal suffixes, so we added a small helper that handles all edge cases:

    • Numbers 11-13 always use "th" (even though 11 ends with 1, it's 11th, not 11st)
    • Digits 1, 2, 3 get "st", "nd", "rd" respectively
    • All other digits use "th"
  2. Fetch Week of Month
    We use $period->weekOfMonth() to get which week of the current month the period falls into. This gives us the "1" in "1st week".

  3. Assemble the Label
    Using sprintf for clean string formatting, we combine:

    • Short month name (via format('M'))
    • Week number + ordinal suffix
    • Full year (via $period->year)

Notes

  • If you need week numbers relative to the year instead of the month (e.g., "Jan 5th week 2021" for the 5th week of the year), replace weekOfMonth() with weekOfYear().
  • Carbon's weekOfMonth() uses the month's natural weeks (starts on your configured week start day, default is Monday). If you need to adjust the week start, you can set it with Carbon::setWeekStartsAt(Carbon::SUNDAY); before creating the period.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 11:42:31