簡體   English   中英

如何使用 CarbonPeriod 將數組從_date 轉換為 to_date 並匹配數組中是否存在另一個日期 php、Laravel

[英]How to Make array from_date to to_date using CarbonPeriod and Match another date is exist in array or not in php , Laravel

我有兩個日期:$from = 2022-11-01 $to = 2022-11-05

現在,我想創建一個這樣的數組: $date = ['2022-11-01','2022-11-02','2022-11-03','2022-11-04','2022-11 -05']

現在檢查 $date 數組中是否存在“2022-11-03”。

已經使用: $date = Carbon\CarbonPeriod::create($from, $to);

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

#但還是不行

您可以只檢查 CarbonPeriod 是否包含您檢查的日期:

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

有人要求使用 CarbonPeriod 解決方案。 但是,如果您只想檢查日期是否介於 $from 和 $to 之間,那么 between 是更好的選擇。

$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;
}

試試碳

如果數據都是yyyy-mm-dd格式,簡單的字符串比較就可以了。

$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;
}

演示: https://3v4l.org/A1IBh

根據問題,您可能沒有使用parse方法來解析日期,所以這可能是問題所在。

        $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();
        }

在這里, $dateArray為您提供了日期數組。

此外,如果部分適用於上述解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM