根据数组中的时间区分输出消息

时间:2018-07-06 21:01:47

标签: php

我正在尝试编写一个脚本,该脚本将根据营业时间显示打开或关闭的消息。我尝试使用解决方案found here,并通过设置时区来添加此解决方案。但是,当我尝试运行此命令时,即使一天中的时间落在数组中的值之内,$ status的值也总是“关闭”。

这是我的代码,任何建议将不胜感激。谢谢

//setting default timezone
date_default_timezone_set('Europe/Dublin');
//creating array of opening hours
$openingHours = [
'Sun' => ['12:00' => '20:30'],
'Wed' => ['16:00' => '21:00'],
'Thu' => ['16:00' => '21:00'],
'Fri' => ['16:00' => '23:00'],
'Sat' => ['16:00' => '21:00']
];



//current timestamp
$timestamp = time();

//default status
$status = 'closed';

//get time object from timestamp
$currentTime = (new DateTime())->setTimestamp($timestamp);

//loop through time range for current day
foreach ($openingHours[date('D', $timestamp)] as $startTime => $endTime) {

//create time objects from start and end times
$startTime = DateTime::createFromFormat('h:i A', $startTime);
$endTime = DateTime::createFromFormat('h:i A', $endTime);

//check if current time is within range
if (($startTime < $currentTime) && ($currentTime < $endTime)) {
$status = 'open';
break;
}//end off if

}//end off foreach

echo "we are currently :$status";

1 个答案:

答案 0 :(得分:0)

在您的代码中,currentTime变量是一个对象,因此当您尝试对其进行比较时,结果将不匹配。尝试一下,这样可以简化一些事情。

date_default_timezone_set('Europe/Dublin');
//creating array of opening hours
$openingHours = [
'Sun' => ['12:00' => '20:30'],
'Wed' => ['16:00' => '21:00'],
'Thu' => ['16:00' => '21:00'],
'Fri' => ['16:00' => '23:00'],
'Sat' => ['16:00' => '21:00']
];

//default status
$status = 'closed';

$timeNow = date('H:m',time());

//loop through time range for current day
foreach ($openingHours[date('D', time())] as $startTime => $endTime) {
    //check if current time is within range
    if (($startTime < $timeNow) && ($timeNow < $endTime)) {
        $status = 'open';
        break;
    }  //end off if
}  //end off foreach

echo "we are currently :$status";
  

在7月7日进行编辑:

如果您可以稍微更改开放时间数组,则可以使用以下代码避免多次调用日期和foreach循环。

date_default_timezone_set('Europe/Dublin');
//creating array of opening hours
$openingHours = [
'Sun' => ['Open'=>'12:00','Close' => '20:30'],
'Wed' => ['Open'=>'16:00','Close' => '21:00'],
'Thu' => ['Open'=>'16:00','Close' => '21:00'],
'Fri' => ['Open'=>'16:00','Close' => '23:00'],
'Sat' => ['Open'=>'16:00','Close' => '21:00']
];

$timeNow = date('H:m',time());
$dow     = date('D',time());

echo 'We are currently :' . ((($openingHours[$dow]['Open'] < $timeNow) AND
                              ($timeNow < $openingHours[$dow]['Close'])) ? 'open' : 'closed');