Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing dates with Carbon

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?

like image 275
Kevin Daniel Avatar asked Jan 27 '16 21:01

Kevin Daniel


People also ask

How do you set the date on carbon?

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.

How do you find the date on a carbon object?

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);

What is carbon :: now ()?

Carbon::now returns the current date and time and Carbon:today returns the current date.


2 Answers

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".

like image 136
ArSeN Avatar answered Sep 28 '22 23:09

ArSeN


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); } 
like image 22
Odin Thunder Avatar answered Sep 28 '22 22:09

Odin Thunder