Antonios Tsimourtos
Antonios Tsimourtos

Reputation: 1672

Carbon loop through specific date range misses one day

SOLUTION :

 $mDatePeriod = new \DatePeriod(

          Carbon::parse("First Monday of January 2018"),
          CarbonInterval::week(),
          Carbon::parse("Last Monday of January 2018")->addSecond(1)
 );

I am running Laravel 5.0 and i am using Carbon library to calculate the below.

Example :

I want to have all Mondays of January of 2018 so i am using the below code :

 $mDatePeriod = new \DatePeriod(

          Carbon::parse("First Monday of January 2018"),
          CarbonInterval::week(),
          Carbon::parse("Last Monday of January 2018")
 );

If i loop through $mDatePeriod and echo the day :

foreach($mDatePeriod as $currentDay){

 echo $currentDay->toDateString() . "<br/>";

}

Output will be :

2018-01-01
2018-01-08
2018-01-15
2018-01-22

Which is not what i am expecting, because 2018-01-29 (last monday) is missing.

If i use dd($mDatePeriod_Day) last monday is shown as the end of the date :

enter image description here

What am i missing here?

EDIT 1 : Found something interesting about CarbonInterval::week(), which has some attributes. Could it be first_last_day_of? :

enter image description here

Upvotes: 0

Views: 1141

Answers (1)

Shiro
Shiro

Reputation: 7544

What you can do is added the time at the last condition

Carbon::parse("Last Monday of January 2018 00:00:01")

Then you can get the date.

Upvotes: 2

Related Questions