php碳检查,如果现在是两次(晚上10点至早上8点)

2022-08-30 18:08:54
$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');

如何检查$now的时间是否在时间范围内?


答案 1

有几种方法可以通过使用碳来实现这一目标。最简单的方法之一是使用 和 方法:createFromTimeStringbetween

$now = Carbon::now();

$start = Carbon::createFromTimeString('22:00');
$end = Carbon::createFromTimeString('08:00')->addDay();

if ($now->between($start, $end)) {
    // ¯\_(ツ)_/¯
}

答案 2

试试这个:

  $time = Carbon::now();
  $morning = Carbon::create($time->year, $time->month, $time->day, 8, 0, 0); //set time to 08:00
  $evening = Carbon::create($time->year, $time->month, $time->day, 18, 0, 0); //set time to 18:00
  if($time->between($morning, $evening, true)) {
    //current time is between morning and evening
  } else {
    //current time is earlier than morning or later than evening
  }

in 检查 是否介于 和 包含 和 之间。如果你写而不是写,它只检查它是否在两个时间之间,但不包括。true$time->between($morning, $evening, true)$time$morning$eveningfalse

实际上,您可以省略它,因为它是默认设置的,不需要。true

查看此处,了解有关如何使用 Carbon 比较日期和时间的更多信息。


推荐