Search code examples
phpdatetimetimephp-carbon

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 = \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');
}

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

Any help?


Solution

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