php carbon check if now is between two times (10pm-8am)
Asked Answered
I

15

26
$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');

How can I check if the time of $now is within the timerange?

Ial answered 26/7, 2017 at 15:22 Comment(1)
If $start and $end are within the same day, $now is not within the range.Adalbert
O
47

There are several ways to achieve that by using Carbon. One of the easiest ways is using createFromTimeString and between methods:

$now = Carbon::now();

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

if ($now->between($start, $end)) {
    // ¯\_(ツ)_/¯
}
Opalopalesce answered 2/1, 2020 at 18:39 Comment(1)
For everyone, who looks of this. Please keep in mind the the method createFromTimeString will always return the current date from an clock like time-input. This really can become to an issue, when you pass midnight. Then in this example, suddenly the next day and the day after tomorrow will become the target date and times. So, you've to put a date-string into the method-parameter and update/store it via database or file.Tishatishri
L
11

Try this:

  $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
  }

The true in $time->between($morning, $evening, true) checks whether the $time is between and including $morning and $evening. If you write false instead it checks just if it is between the two times but not including.

Actually, you could leave true away because it is set by default and not needed.

Check here for more information on how to compare dates and times with Carbon.

Lanita answered 10/1, 2018 at 21:13 Comment(0)
E
8
$start = '22:00:00';
$end   = '08:00:00';
$now   = Carbon::now('UTC');
$time  = $now->format('H:i:s');

if ($time >= $start && $time <= $end) {
    ...
}

Should do it, but doesn't take date into consideration

Estebanesteem answered 26/7, 2017 at 15:52 Comment(3)
Your OR logic is wrong. It should be AND. If now is 13:00:00 and range is 12:00:00 to 12:45:00, then your solution would answer yes because $time is actually >= $start.Arias
If you consider the time as "23:00:00", your logic is going to be wrong.Birnbaum
@Birnbaum care to explain? "23:00:00" is greater than the start time of "22:00:00", so the logic checks out to meEstebanesteem
I
4

You can reverse check algorithm.

<?php
$pushChannel = "general";

$now = Carbon::now();

$start = Carbon::createFromTime(8, 0);
$end = Carbon::createFromTime(22, 0);

if (!$now->between($start, $end)) {
     $pushChannel = "silent";
Ize answered 10/11, 2020 at 5:51 Comment(0)
C
2
$restrictStartTime = Carbon::createFromTime(22, 0, 0);  //carbon inbuild function which will create todays date with the given time
$restrictEndTime = Carbon::createFromTime(8, 0, 0)->addDays(1); //this will create tomorrows date with the given time
$now = Carbon::now();

if($now->gt($restrictStartTime) && $now->lt($restrictEndTime)) {
 .....
 }
Chiliarch answered 23/3, 2018 at 10:58 Comment(2)
While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.Gretchengrete
I suggest you to explain how to automatically convert the $start = '22:00:00'; bit into what you proposed $restrictStartTime = Carbon::createFromTime(22, 0, 0);Realist
S
1

Please Try below code,

$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');

$nowTime = $now->hour.':'.$now->minute.':'.$now->second;

if(strtotime($nowTime) > strtotime($start) && strtotime($nowTime) < strtotime($end) ) {
    echo 'YES';
} else {
    echo 'NO';
}
Sundsvall answered 26/7, 2017 at 15:54 Comment(2)
Does not solve the date range problem (i.e. $now > $start && $now < $end is not sufficient)Ial
Actually do you want to range time? isn't it ? Please try answer code again. if it is not solve describe me.Sundsvall
R
1

What Chris is trying to point out is if the endtime crosses over midnight then you must account for that.

This is not the cleanest way to do it but here is a method that seems to work.

private function isNowBetweenTimes($timezone, $startDateTime, $endDateTime) {
    $curTimeLocal = Carbon::now($timezone);
    $startTime = $curTimeLocal->copy();
    $startTime->hour = $startDateTime->hour;
    $startTime->minute = $startDateTime->minute;
    $endTime = $curTimeLocal->copy();
    $endTime->hour = $endDateTime->hour;
    $endTime->minute = $endDateTime->minute;
    if ($endTime->lessThan($startTime))
        $endTime->addDay();

    return ($curTimeLocal->isBetween($startTime, $endTime));
}

This example only cares about the hour and minutes and not the seconds but you can easily copy that as well. The key to this is comparing start and end time before comparing them to the current time and add a day to end time if end time is less than start time.

Romaromagna answered 26/7, 2019 at 3:38 Comment(0)
S
1

For complete solution which supports all start and end time range you can use bitwise XOR.

/*
 * must using hours in 24 hours format e.g. set 0 for 12 pm, 6 for 6 am and 13 for 1 pm
 */
private $startTime = '0';
private $endTime = '6';
    

$currentHour = \Carbon\Carbon::now()->hour;
$start = $this->startTime > $this->endTime ? !($this->startTime <= $currentHour) : $this->startTime <= $currentHour;
$end = $currentHour < $this->endTime;


if (!($start ^ $end)) {
  //Do stuff here if you want exactly between start and end time
}
Sturgis answered 13/1, 2021 at 7:45 Comment(0)
T
1

Yes, the midnight plays a vital role in time duration. We can find now() being the given time range as follows:

$now = Carbon::now();
$start = Carbon::createFromTime('22', '00');
$end = Carbon::createFromTime('08', '00');

if ($start->gt($end)) {
    if ($now->gte($start)) {
        $end->addDay();
    } elseif ($now->lte($end)) {
        $start->subDay();
    } else {
        return false;
    }
}

return $now->between($start, $end);
Tintinnabulum answered 22/3, 2022 at 21:59 Comment(1)
Very nice and neat , thank youApostrophize
F
1

an updated version of @AliN11's answer taking into account ranges accross two days or in the same day

$now = now();

$start = Carbon::createFromTimeString('22:00');
$end = Carbon::createFromTimeString('08:00');
if ($start > $end) {
    $end = $end->addDay();
}
if ($now->between($start, $end)||$now->addDay()->between($start, $end)) {
   //add statements
}
Fusee answered 6/7, 2022 at 9:12 Comment(0)
P
0

Try this :

$start = 22; //Eg. start hour
$end = 08;  //Eg. end hour
$now = Carbon::now('UTC');

if( $start < $now->hour && $now->hour < $end){
    // Do something
}
Perspective answered 26/7, 2017 at 15:28 Comment(1)
That's not valid phpIal
T
0
<?php
$now = date("H");

if ($now < "20") {
    echo "Have a good day!";
}
Told answered 26/7, 2017 at 15:29 Comment(1)
Does not solve the date range problem (i.e. $now > $start && $now < $end is not sufficient)Ial
M
0

@AliN11's (currently top) answer is good, but doesn't work as one would immediately expect, after midnight it just breaks, as raised in the comments by @Sasha

The solution is to reverse the logic, and check if the time is not between the inverse hours.

Here is an alternative that works as one would expect:

    $now = Carbon::now();
    $start = Carbon::createFromTimeString('08:00');
    $end = Carbon::createFromTimeString('22:00');

    if (! $now->between($start, $end)) {
        // We're all good
    }
Merrillmerrily answered 26/2, 2022 at 12:42 Comment(0)
C
0

If you have an initial value to check the time interval you can initiate it with Carbon's copy() method and set the hours and minutes with setHours() and setMinutes(). After that, just use the regular between().

For example, checking if "2022-01-28 19:00" is >= 07:00 and < 19:00.

$fromRequest = "2022-01-28 19:00";
$from = Carbon::parse($fromRequest);
$start = $from->copy()->setHours(7)->setMinutes(0);
$end = $from->copy()->setHours(18)->setMinutes(59);
$this->isDaytime = $from->between($start, $end); // false
Cienfuegos answered 9/3, 2023 at 3:26 Comment(0)
L
0

Laravel and PHP using carbon that time between used like this

$startDate = Carbon::createFromFormat('H:i a', '08:00 AM');
$endDate = Carbon::createFromFormat('H:i a', '07:00 PM');
$check = Carbon::now()->between($startDate, $endDate, true);
if($check){
    dd('In Between');
}else{
    dd('In Not Between');
}
Laevorotation answered 21/4, 2023 at 7:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.