如何在 Lumen 中使用 Carbon 创建一个函数来检查当前时间是否在晚上 11 点到早上 7 点之间?
How to make a function using Carbon in Lumen to check if current time is between 11pm to 7am?
可以找到此信息 in the Carbon docs。如何实现?
To determine if the current instance is between two other instances you can use the aptly named between()
method. 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.
$first = Carbon::create(2012, 9, 5, 1);
$second = Carbon::create(2012, 9, 5, 5);
var_dump(Carbon::create(2012, 9, 5, 3)->between($first, $second)); // bool(true)
var_dump(Carbon::create(2012, 9, 5, 5)->between($first, $second)); // bool(true)
var_dump(Carbon::create(2012, 9, 5, 5)->between($first, $second, false)); // bool(false)
由于您的时间段跨越日标记,检查相反的情况可能更容易:
$first = Carbon::now()->setTime(7,0,0);
$second = Carbon::now()->setTime(23,0,0);
$now = Carbon::now();
if(!$now->between($first, $second)) {
// Time is not between 7am and 11pm, so do your checks here
}
可以找到此信息 in the Carbon docs。如何实现?
To determine if the current instance is between two other instances you can use the aptly named
between()
method. 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.$first = Carbon::create(2012, 9, 5, 1); $second = Carbon::create(2012, 9, 5, 5); var_dump(Carbon::create(2012, 9, 5, 3)->between($first, $second)); // bool(true) var_dump(Carbon::create(2012, 9, 5, 5)->between($first, $second)); // bool(true) var_dump(Carbon::create(2012, 9, 5, 5)->between($first, $second, false)); // bool(false)
由于您的时间段跨越日标记,检查相反的情况可能更容易:
$first = Carbon::now()->setTime(7,0,0);
$second = Carbon::now()->setTime(23,0,0);
$now = Carbon::now();
if(!$now->between($first, $second)) {
// Time is not between 7am and 11pm, so do your checks here
}