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
}
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With