4

All I want to check if current time is between 2 times

I browsed multiple scripts so far but all the scripts include also the date or is just to difficult, or the script counts only full hours like 6 or 7, while I need to check with hour and minutes

I would appreciate the help, the script setting I would like is

$begintime = 8:30;
$endtime = 17:00;

if(currenttime is between $begintime and $endtime) {
    // do something
} else {
    // do something else
}
jotik
  • 17,044
  • 13
  • 58
  • 123
user2461508
  • 113
  • 1
  • 1
  • 6
  • private function is_between_times($from, $to) { $Carbon = new Carbon(); $from = $Carbon->createFromFormat('H:i:s', $from); $to = $Carbon->createFromFormat('H:i:s', $to); return $Carbon->now()->between($from, $to); } – Marlon Bernal Jul 22 '18 at 03:16

3 Answers3

12

Use DateTime object in the definition. It will internally use current date which can be then ignored in comparison.

$now = new DateTime();
$begin = new DateTime('8:00');
$end = new DateTime('17:00');

if ($now >= $begin && $now <= $end)

Advanced: for this to be bulletproof even when date changes during execution (DateTime objects can some have a 1-day-off date), re-set the date from the $now to the $start and $end DateTime object to:

$y = (int) $now->format('Y');
$m = (int) $now->format('n'); // n is the month without leading zeros
$d = (int) $now->format('d');

$begin->setDate($y, $m, $d);
$end->setDate($y, $m, $d);

Alternatively, check the Brick\DateTime extensions where LocalTime class can be found which ignores date.

Finwe
  • 6,372
  • 2
  • 29
  • 44
4

Check out the DateTime function of PHP.

$now = new Datetime("now");
$begintime = new DateTime('08:30');
$endtime = new DateTime('17:00');

if($now >= $begintime && $now <= $endtime){
    // between times
    echo "yay";
} else {
    // not between times
    echo "nay";
}

Also, make sure that your timezone is correctly set in your php.ini. Or you can set it on runtime with date_default_timezone_set();

Sam
  • 169
  • 2
  • 12
0

Check out. I test this code. It works fine.

date_default_timezone_set("Asia/Kolkata");
$current_time = date("h:i a");
$begin = "9:00 am";
$end   = "5:00 pm";

$date1 = DateTime::createFromFormat('H:i a', $current_time);
$date2 = DateTime::createFromFormat('H:i a', $begin);
$date3 = DateTime::createFromFormat('H:i a', $end);

if ($date1 > $date2 && $date1 < $date3) {
   echo 'Here';
} else {
   echo 'Not';
}
Rahul Chauhan
  • 1,424
  • 14
  • 13