[英]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;
}
根據問題,您可能沒有使用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.