我正在尝试在基于Wordpress的网站上打开商家并从数据库中提取信息时显示通知。数据仅作为单独的数据库条目存储为每天的打开/关闭时间。当小时在一天之内时,它是相当直接的。但对于酒吧/餐厅而言,它变得复杂,因为技术上是在第二天关闭时间。我将以星期二为例。
$tuesdayopen = strtotime("10:00");
$tuesdayclose = strtotime("23:00");
$now = strtotime("now");
if ($now >= $tuesdayopen && $now <= $tuesdayclose) {
echo "We are open!";
} else {
echo "We are closed!";
}
所以这样可以正常工作。如果关闭时间是第二天,我也有一个不太优雅的解决方案。
$tuesdayopen = strtotime("10:00");
$tuesdayclose = strtotime("02:00");
$now = strtotime("now");
if ($tuesdayclose >= strtotime("00:00") && $tuesdayclose <= strtotime("04:00")):
$tuesdayclose = strtotime("+1 day", $tuesdayclose);
endif;
if ($now >= $tuesdayopen && $now <= $tuesdayclose) {
echo "We are open!";
} else {
echo "We are closed!";
}
那我的问题在哪里?问题是$ now现在最终是在午夜之后。因此,如果有人在周二晚上,午夜之后访问该页面,那么技术上是周三早上。这意味着我的完整脚本将继续到周三。我需要它认识到它是在午夜和凌晨4点之间,因此,使用前几天的开放/关闭时间来确定它是否打开(但只有在关闭时间是在午夜之后,否则转到星期三是正确的事情去做)。希望我解释得那么好。我自己尝试过写一些东西,但是代码是一个臃肿的混乱,最终无法正常工作。所以我不打算在这里包括它。
答案 0 :(得分:3)
我会创建一个数组,其中包含该地点已打开并循环播放的数组。另外一个优点是,如果一个地方在午餐时间关闭,它很容易添加。
请注意,无论时间是将来还是过去,我都会将从周一00:00开始计算秒数的时间标准化。
<?php
// Normalize time to count from 0
function timeOfWeek($time) {
if (!is_int($time)) $time = strtotime($time) ;
$secondsInWeek = (7 * 24 * 3600);
return (($time - strtotime('monday 00:00')) % $secondsInWeek + $secondsInWeek) % $secondsInWeek;
}
function isOpen($opened, $time) {
$time = timeOfWeek($time);
foreach ($opened as $openday) {
list($open, $close) = $openday;
if ($open < $close) {
if ($time > $open && $time < $close) return true;
} else {
if ($time > $open || $time < $close) return true; // Special case sunday -> monday
}
}
return false;
}
$opened = array();
$opened[] = array(timeOfWeek('monday 10:00'), timeOfWeek('monday 23:00'));
$opened[] = array(timeOfWeek('tuesday 10:00'), timeOfWeek('tuesday 23:00'));
$opened[] = array(timeOfWeek('wednesday 10:00'), timeOfWeek('wednesday 23:00'));
$opened[] = array(timeOfWeek('thursday 10:00'), timeOfWeek('thursday 23:00'));
$opened[] = array(timeOfWeek('friday 10:00'), timeOfWeek('saturday 01:00'));
$opened[] = array(timeOfWeek('saturday 10:00'), timeOfWeek('sunday 01:00'));
$opened[] = array(timeOfWeek('sunday 10:00'), timeOfWeek('monday 01:00'));
$open = isOpen($opened, time());
var_dump($open);
答案 1 :(得分:-2)
只需将时区转换为yourTimeZone-4h!