Carbon 检查当前时间是否介于两个时间之间

Carbon check if current time between two time

我想查看当前时间是否在上午 8 点到晚上 8 点之间。到目前为止,我已经试过了

 $startTime = \Carbon\Carbon::createFromFormat('H:i a', '08:00 AM')->toString();
$endTime = \Carbon\Carbon::createFromFormat('H:i a', '08:00 PM')->toString();
$currentTime = \Carbon\Carbon::now();
if($currentTime->greaterThan($startTime) && $currentTime->lessThan($endTime)){
    dd('In Between');
}else{
    dd('In Not Between');
}

但是因为carbon date是date类型,另外一个是string类型,没法比较

有什么帮助吗?

$now = Carbon::now();

$start = Carbon::createFromFormat('H:i a', '08:00 AM');
$end =  Carbon::createFromFormat('H:i a', '08:00 PM');


if ($now->isBetween($start, $end) {
  // between 8:00 AM and 8:00 PM
} else {
  // not between 8:00 AM and 8:00 PM
}

To determine if the current instance is between two other instances you can use the aptly named between() method (or isBetween() alias). The third parameter indicates if an equal to comparison should be done. The default is true which determines if its between or equal to the boundaries.