How to make a period with all months between two random dates? I tried:
$startDate = \Carbon\Carbon::parse('2021-11-17 23:59:59');
$endDate = \Carbon\Carbon::parse('2022-01-10 00:00:00');
$period = \Carbon\CarbonPeriod::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 = \Carbon\Carbon::parse('2021-11-17 23:59:59');
$endDate = \Carbon\Carbon::parse('2022-01-31 00:00:00');
$period = \Carbon\CarbonPeriod::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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.