phpdatetimephp-carbon

Split CarbonPeriod into days (PHP)


I have this CarbonPeriod with start 2025-06-09 19:00 and end 2025-06-11 11:00. What I want is an array of the days with start and end date. So basicly an array like this, possibly with new CarbonPeriods:

[
  [
    'start' => 2025-06-09 19:00:00
    'end' => 2025-06-09 23:59:59:9999
  ],
  [
    'start' => 2025-06-10 00:00:00
    'end' => 2025-06-10 23:59:59:9999
  ],
  [
    'start' => 2025-06-11 00:00:00
    'end' => 2025-06-11 11:00:00
  ]
]

What is the best way to achieve this?

EDIT:

Iterating over the CarbonPeriod won't work, because it will use the time of the first item in all items:

[
  ['date' => 2025-06-09 19:00:00]
  ['date' => 2025-06-10 19:00:00]
  ['date' => 2025-06-11 19:00:00]
]

Solution

  • use Carbon\Carbon;
    use Carbon\CarbonPeriod;
    
    $start = Carbon::parse('2025-06-09 19:00');
    $end = Carbon::parse('2025-06-11 11:00');
    
    $days = [];
    $current = $start->copy();
    
    while ($current->lessThan($end)) {
        $dayStart = $current->copy();
        if ($current->isSameDay($end)) {
           
            $dayEnd = $end->copy();
        } else {
           
            $dayEnd = $current->copy()->endOfDay();
        }
        $days[] = CarbonPeriod::create($dayStart, $dayEnd);
        $current = $dayEnd->copy()->addSecond();
    }