Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check time between two times [duplicate]

Tags:

php

time

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
}
like image 658
user2461508 Avatar asked Dec 11 '22 16:12

user2461508


2 Answers

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.

like image 72
Finwe Avatar answered Dec 26 '22 21:12

Finwe


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();

like image 31
Sam Avatar answered Dec 26 '22 22:12

Sam