Reputation: 1044
I'm getting the opening and closing time of a store in HHMM format (0000 to 2359):
$openingtime = intval($open->time);
$closingtime = intval($close->time);
Then I get the current time in the same format:
$nowtime = intval(date("G") . date("i"));
I want to know whether the current time is between 15 minutes before the opening time, and 45 minutes before the closing time.
I have this, but it is inaccurate:
if(($nowtime >= ($openingtime - 15)) && ($nowtime <= ($closingtime - 45))){
// current time is between 15 minutes before opening and 45 minutes before closing
}
If the time is 2300, then 2300 - 15 = 2285, which isn't a valid time.
How can I resolve this?
Also, I assume I need to do something at the overlap of the day (0000), but I'm not sure what I need to do there.
Upvotes: 0
Views: 89
Reputation: 1844
You can create DateTime
object like that:
$open = date_create_from_format('Hi', '1000');
$close = date_create_from_format('Hi', '1900');
Then you can use DateTimeInterval
$interval15 = new \DateInterval('P0Y0DT0H15M');
$interval45 = new \DateInterval('P0Y0DT0H45M');
Then you can sub it from closing time and from open:
$now = new DateTime();
if ($now >= $open->sub($interval15) && $now <= $close->sub($interval45)) {
// logic
}
Upvotes: 2
Reputation: 14259
You should convert from HHMM into minutes and then compare minutes with minutes
$time_open = str_pad($openingtime, 4, '0', STR_PAD_LEFT);
$time_close = str_pad($closingtime, 4, '0', STR_PAD_LEFT);
$open_minutes = substr($time_open,0,2) * 60 + substr($time_open,2,2);
$close_minutes = substr($time_close,0,2) * 60 + substr($time_close,2,2);
$nowtime = date("G") * 60 + date("i");
if($nowtime >= $open_minutes - 15 AND $nowtime <= $close_minutes - 45)
{
// do your stuff
}
Upvotes: 1