4

我试图在基于 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 点之间,因此,使用前几天的开放/关闭时间来确定它是否开放(但前提是关闭时间是在午夜之后,否则转到星期三是正确的去做)。希望我解释得很好。我试过自己写一些东西,但代码是一团糟,最终不起作用。所以我不会费心把它包括在这里。

4

2 回答 2

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);
于 2013-01-02T01:41:41.043 回答
-2

只需将时区转换为 yourTimeZone-4h!

于 2013-01-02T01:14:05.287 回答