Home > Back-end >  How to Make array from_date to to_date using CarbonPeriod and Match another date is exist in array o
How to Make array from_date to to_date using CarbonPeriod and Match another date is exist in array o

Time:11-17

i have two date : $from = 2022-11-01 $to = 2022-11-05

now , i wanna create a array like this : $date = ['2022-11-01','2022-11-02','2022-11-03','2022-11-04','2022-11-05']

and now check '2022-11-03' is exist in $date array or not.

alrady use : $date = Carbon\CarbonPeriod::create($from, $to);

if(in_array('2022-11-03', $date)){
    echo "Got it";
}

#But Still not Work

CodePudding user response:

You can just check if the CarbonPeriod contains the date you check:

$from = '2022-11-01';
$to = '2022-11-05';
$date = Carbon\CarbonPeriod::create($from, $to);
if ($date->contains('2022-11-03')) {
    echo 'Got it';
}

CodePudding user response:

Based on the question it could be that you aren't using parse method to parse dates, so this could be the problem.

        $from = "2022-11-01";
        $to = "2022-11-05";
        $dates = CarbonPeriod::create(
            Carbon::parse($from),
            Carbon::parse($to),
        );
        $dateArray = [];
        foreach ($dates as $date) {
            $dateArray[] = $date->toDateString();
        }

Here, $dateArray provides you with the dates array.

Furthermore the if section works correctly for the above solution:

if(in_array('2022-11-03', $date)){
    echo "Got it";
}

CodePudding user response:

It was asked for a solution with CarbonPeriod. However, if you only want to check if a date is between $from and $to, between is the better choice.

$from = "2022-11-01";
$to = "2022-11-05";
$check = "2022-11-03";
if(Carbon::parse($check)->between($from,$to)){
  echo $check.' is between '.$from.' and '.$to;
} else {
  echo $check.' is not between '.$from.' and '.$to;
}

between($from,$to)){ echo $check.' is between '.$from.' and '.$to; } else { echo $check.' is not between '.$from.' and '.$to; }&token=live-editor-120" rel="nofollow noreferrer">Try Carbon

If the data is all in the format yyyy-mm-dd, a simple string comparison is sufficient.

$from = "2022-11-01";
$to = "2022-11-05";
$check = "2022-11-03";
if($from <= $check AND $check <= $to) {
  echo $check.' is between '.$from.' and '.$to;
} else {
  echo $check.' is not between '.$from.' and '.$to;
}

Demo: https://3v4l.org/A1IBh

  • Related