Carbon Period Laravel: Examples of Date Time Lists For Reports and Calendars Laravel

Loading

Carbon class for date & time are well known that comes with Laravel, but there is also one more carbon class named as CarbonPeriod. It can also create an ARRAY of datetimes, use for example in report tables and calendars. Today during this tutorial we are going to looking at example with the help of CarbonPeriod in Laravel PHP.

List of Hours Or Minute Intervals

What if you need an array list of working hours limited by start/end times?

  • 9:00
  • 10:00
  • 11:00
  • 18:00

Look at this CarbonInterval snippet:

use Carbon\Carbon;
use Carbon\CarbonPeriod;
 
$startPeriod = Carbon::parse('9:00');
$endPeriod   = Carbon::parse('18:00');
 
$period = CarbonPeriod::create($startPeriod, '1 hour', $endPeriod);
$hours  = [];
 
foreach ($period as $date) {
    $hours[] = $date->format('H:i');
}

Result:

array:10 [
  0 => "09:00"
  1 => "10:00"
  2 => "11:00"
  3 => "12:00"
  4 => "13:00"
  5 => "14:00"
  6 => "15:00"
  7 => "16:00"
  8 => "17:00"
  9 => "18:00"
]

You can see here, eachย CarbonPeriodย element is aย Carbonย class instance that you can format however you want.

But it’s not necessarily about the hours only. You can also change the period to smaller intervals, like “45 minutes”:

$period = CarbonPeriod::create($startPeriod, '45 minutes', $endPeriod);

Result:

array:13 [
  0 => "09:00"
  1 => "09:45"
  2 => "10:30"
  3 => "11:15"
  4 => "12:00"
  5 => "12:45"
  6 => "13:30"
  7 => "14:15"
  8 => "15:00"
  9 => "15:45"
  10 => "16:30"
  11 => "17:15"
  12 => "18:00"
]

You can also skip the first or last entry using theย excludeStartDateย orย excludeEndDateย methods.

$period = CarbonPeriod::create($startPeriod, '45 minutes', $endPeriod)
    ->excludeStartDate()
    ->excludeEndDate();
array:11
  0 => "09:45"
  1 => "10:30"
  2 => "11:15"
  3 => "12:00"
  4 => "12:45"
  5 => "13:30"
  6 => "14:15"
  7 => "15:00"
  8 => "15:45"
  9 => "16:30"
  10 => "17:15"
]

Or change representation to a 12-hour format:

foreach ($period as $date) {
    $hours[] = $date->format('h:i A');
}
array:11 [
  0 => "09:45 AM"
  1 => "10:30 AM"
  2 => "11:15 AM"
  3 => "12:00 PM"
  4 => "12:45 PM"
  5 => "01:30 PM"
  6 => "02:15 PM"
  7 => "03:00 PM"
  8 => "03:45 PM"
  9 => "04:30 PM"
  10 => "05:15 PM"
]

Above mentioned examples are showing how we can use CarbonPeriod to generate timing according to specific date and time

About Post Author