[英]Laravel Carbon get next occurrence of particular hour from current date
I want write a code that give me next occurrence of hour from current time.我想编写一个代码,让我从当前时间开始下一个小时。
Eg Give closest next 8:00 am.例如,给最近的下一个上午 8:00。
Scenario 1:场景一:
Input :输入:
$currentTime = '11-26-2020 20:00'; // MM-DD-YYYY H:i
Expected Output :预期 Output :
$closest8am = '11-27-2020 8:00';
Scenario 2:场景二:
Input :输入:
$currentTime = '11-27-2020 01:00'; // MM-DD-YYYY H:i
Expected Output :预期 Output :
$closest8am = '11-27-2020 8:00';
Thank You in advance.先感谢您。
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);
I will suggest you to use the next()
Carbon method.我会建议你使用next()
Carbon 方法。
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亲切地
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.