I'm trying to create an array of blackout dates for a reservation system in Laravel 4. There is one test row in my db with a start_date of 2016-01-24 and end_date of 2016-01-29.
This is the code that pulls the row and loops through the dates using Carbon to increment by one day & add it to an array:
$reserved = Reservation::where('property_id', $property->id)->get(); $blackoutDays = []; foreach($reserved as $r) { $start = new \Carbon\Carbon($r->start_date); $end = new \Carbon\Carbon($r->end_date); $days = $start->diff($end)->days; for($i = 0; $i <= $days; $i++) { $date = ''; $date = $start->addDays($i); $blackoutDays[] = $date->format('Y-m-j'); } }
What I'm trying to get in $blackoutDays is:
["2016-01-24", "2016-01-25", "2016-01-26", "2016-01-27", "2016-01-28", "2016-01-29"]
But what I'm actually getting is this:
["2016-01-24", "2016-01-25", "2016-01-27", "2016-01-30", "2016-02-3", "2016-02-8"]
Does anyone know why this is happening / how to fix it? Is there a better way of doing this?
Carbon also allows us to generate dates and times based on a set of parameters. For example, to create a new Carbon instance for a specific date use the Carbon::createFromDate() method, passing in the year, month, day, and timezone, as in the following example.
You can use array_map to produce this kind of result: $dates_formatted = array_map(function($entry) { // transform the Carbon object to something like 'Dec 25, 1975' return $entry['date']->toFormattedDateString(); }, $dates);
Carbon::now returns the current date and time and Carbon:today returns the current date.
You do increment $i
every run of your for loop. So it adds 1 in the first run, 2 days in the second, 3 days in the third and so on.
Therefore, you want to replace
$date = $start->addDays($i);
with
$date = $start->addDays(1);
Where you probably fell into the pit is the idea that the days are added from the $start
date object on every call, but this is not the case, as this object is not "Immutable".
For more cleaner result, you can use addDay() method:
$date = $start->addDay();
But in fact this is exactly the same. Source code for addDay() method:
/** * Add a day to the instance * * @param int $value * * @return static */ public function addDay($value = 1) { return $this->addDays($value); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With