Skip to content
Advertisement

Carbon check if current time between two time

I want to check if current time between at 8 am and 8 pm. So far, I’ve tried

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

But because of carbon date has date type and the other time has string type I can’t compare them.

Any help?

Advertisement

Answer

$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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement