How to create a range of dates ?
What do you mean?
i want for exemple, create a range of dates between today and today + 20 days
You mean like if you do Carbon::parse('+20 days')->diff() ? Like a DateInterval object ?
A very primitive example:
class DateRange {
public Carbon $start;
public Carbon $end;
public function __construct(Carbon $start, Carbon $end) {
$this->start = $stard;
$this->end= $end;
}
}
$todayToPlus20 = new DateRange(Carbon::now(), Carbon::now()->addDays(20));
echo $todayToPlus20->start;
echo $todayToPlus20->end;
If its an array of 20 dates you are after to just add them to an array ??
$start = Carbon::now(); // use your start here
for ($i = 0 ; $i < 20 ; $i++) {
$dates[] = $start->copy();
$start->addDay();
}
what i want is an array of dates between $startDate and $endDate:
$startDate = Carbon::now(); $endDate = '2014-07-30'; // result array($startDate, $startDate+1day, $startDate+2day,..., $endDate);
briannesbitt's answer works in your case, replace juste $i < 20 with something like $start->format('Y-m-d') != $endDate.
$start = Carbon::today();
$end = new Carbon('2014-07-30');
$end->startOfDay();
$dates = array();
while ($start->lte($end)) {
$dates[] = $start->copy();
$start->addDay();
}
... and if you wanted it shorter (but harder to read IMO)
$start = Carbon::yesterday();
$end = new Carbon('2014-07-30');
$end->startOfDay();
$dates = array();
while ($start->lte($end)) {
$dates[] = $start->addDay()->copy();
}
Nice :+1:
thank you @briannesbitt
This can also be done like this:
new DatePeriod($startDate, new DateInterval('P1D'), $endDate)
Just keep in mind that DatePeriod is an iterator, so if you want an actual array:
iterator_to_array(new DatePeriod($startDate, new DateInterval('P1D'), $endDate))
In you're using Laravel, you could always create a Carbon macro:
Carbon::macro('range', function ($start, $end) {
return new Collection(new DatePeriod($start, new DateInterval('P1D'), $end));
});
Now you can do this:
foreach (Carbon::range($start, $end) as $date) {
// ...
}
Will be added to the documentation:
https://github.com/briannesbitt/Carbon/compare/gh-pages...kylekatarnls:gh-pages-1.26
Most helpful comment
This can also be done like this:
Just keep in mind that
DatePeriodis an iterator, so if you want an actual array:In you're using Laravel, you could always create a Carbon macro:
Now you can do this: