Skip to content
Advertisement

Laravel. CarbonPeriod. All “unical” months between two dates

How to make a period with all months between two random dates? I tried:

$startDate = CarbonCarbon::parse('2021-11-17 23:59:59');
$endDate = CarbonCarbon::parse('2022-01-10 00:00:00');

$period = CarbonCarbonPeriod::create($startDate, '1 month', $endDate);

foreach($period as $month)
{
    echo '<pre>'.$month->format('Y-m-d').'</pre>';
}

but it doesn’t include January.

I also tried to use floor():

$startDate = CarbonCarbon::parse('2021-11-17 23:59:59');
$endDate = CarbonCarbon::parse('2022-01-31 00:00:00');

$period = CarbonCarbonPeriod::create($startDate, '1 month', $endDate)->floor();

foreach($period as $month)
{
    echo '<pre>'.$month->format('Y-m-d').'</pre>';
}

but it includes February that don’t even need.

How to get pure “unical” months between two dates using CarbonPeriod?

For example: start_date: 2021-11-17 23:59:59 & end_date: 2022-01-10 00:00:00 -> 11, 12, 01

Also: start_date: 2021-11-17 23:59:59 & end_date: 2022-01-31 00:00:00 -> 11, 12, 01

Thank you.

Advertisement

Answer

use startOfMonth() and endOfMonth() as below.

    $startDate = Carbon::parse('2021-11-17 23:59:59')->startOfMonth();
    $endDate = Carbon::parse('2022-01-10 00:00:00')->endOfMonth();
    
    foreach (CarbonPeriod::create( $startDate, '1 month', $endDate) as $month) {
         echo  $month->format('m') . PHP_EOL;
    }

Output will be: 11 12 01

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement