简体   繁体   中英

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 :

在此处输入图片说明

What am i missing here?

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

在此处输入图片说明

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM