Laravel Carbon get next occurrence of particular hour from current date

Viewed 642

I want write a code that give me next occurrence of hour from current time.

E.g Give closest next 8:00 am.

Scenario 1 :

Input :

$currentTime = '11-26-2020 20:00'; // MM-DD-YYYY H:i

Expected Output :

$closest8am = '11-27-2020 8:00';

Scenario 2 :

Input :

$currentTime = '11-27-2020 01:00'; // MM-DD-YYYY H:i

Expected Output :

$closest8am = '11-27-2020 8:00';

Thank You in advance.

2 Answers

I will suggest you to use the next() Carbon method.
Full example from the doc:

$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
echo $dt->next(Carbon::WEDNESDAY);                 // 2012-02-01 00:00:00
var_dump($dt->dayOfWeek == Carbon::WEDNESDAY);     // bool(true)
echo $dt->next('Wednesday');                       // 2012-02-08 00:00:00
echo $dt->next('04:00');                           // 2012-02-08 04:00:00
echo $dt->next('12:00');                           // 2012-02-08 12:00:00
echo $dt->next('04:00');                           // 2012-02-09 04:00:00

$dt = Carbon::create(2012, 1, 1, 12, 0, 0);
echo $dt->next();                                  // 2012-01-08 00:00:00

Cordially

Try the following code.

function getNextClosestTime($currentTime, $hour){
        $get_hour = date("H",strtotime($currentTime));
        if($get_hour<=$hour){
            $next_closest_time = date("m-d-y $hour:00",strtotime($currentTime))  ;
        }else{
            $next_closest_time = date("m-d-y $hour:00",strtotime($currentTime ." + 1 day"))  ;
        }
        return $next_closest_time;
    }
    $currentTime = '11/27/2020 20:00'; 
    echo getNextClosestTime($currentTime,8);
    echo "++++++++";
    $currentTime = '11/27/2020 01:00'; 
    echo getNextClosestTime($currentTime,8);
Related