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
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"
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".Assemble the Label
Usingsprintffor clean string formatting, we combine:- Short month name (via
format('M')) - Week number + ordinal suffix
- Full year (via
$period->year)
- Short month name (via
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()withweekOfYear(). - 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 withCarbon::setWeekStartsAt(Carbon::SUNDAY);before creating the period.
内容的提问来源于stack exchange,提问作者Ray Coder
相关产品推荐
相关产品推荐

