要动态确定要显示的时间日期,您需要通过检查今天的结束日期是否大于当前时间,对前一个日期的结束时间执行消除过程。
但是由于关闭时间不包括星期几,您还必须验证关闭时间是am,以避免误报。
public static function Today() {
$currentDate = new \DateTimeImmutable;
$priorDate = $currentDate->sub(new \DateTimeInterval('P1D'));
$yesterday = $priorDate->format('l');
$priorClosing = self::setting('closing_time_' . $yesterday);
$closeDate = $currentDate->setTime(...explode(':', $priorClosing));
if ($closeDate->format('a') === 'am' && $currentDate < $closeDate) {
//check if the closing has not occurred yet
$currentDate = $priorDate;
}
$today = $currentDate->format('l');
$start = self::setting('opening_time_' . $today);
$end = self::setting('closing_time_' . $today);
return $start . " - " . $end;
}
结果:
Day | 00:15:00 | 23:00:00
Monday | Monday: 09:30 - 01:30 | Monday: 09:30 - 01:30
Tuesday | Monday: 09:30 - 01:30 | Tuesday: 09:30 - 01:30
Wednesday | Tuesday: 09:30 - 01:30 | Wednesday: 09:30 - 01:30
Thursday | Wednesday: 09:30 - 01:30 | Thursday: 09:30 - 01:30
Friday | Thursday: 09:30 - 01:30 | Friday: 09:30 - 23:00
Saturday | Saturday: 10:30 - 00:00 | Saturday: 10:30 - 00:00
Sunday | Sunday: 10:30 - 00:00 | Sunday: 10:30 - 00:00
(每种方法都相同,但结果会因使用的开盘截止日期而异)
根据您当前的营业时间结构,当开盘日期和收盘日期的时间均为AM 时,上述示例将提供误报。
避免这种情况的唯一方法是在给定日期的开始和结束时间中包含星期几。
(最准确 - 如果操作持续时间不超过 24 小时)
解决前一天在AM 中开始和结束时出现误报的问题。问题是关闭一天是未知的,并且假设操作持续时间始终少于 24 小时。您还可以比较前一个日期的开放时间和结束日期,并确保它们不超过 24 小时。
public static function Today() {
$currentDate = new \DateTimeImmutable;
$priorDate = $currentDate->sub(new \DateTimeInterval('P1D'));
$yesterday = $priorDate->format('l');
$priorOpening = self::setting('opening_time_' . $yesterday);
$priorClosing = self::setting('closing_time_' . $yesterday);
$priorOpenDate = $priorDate->setTime(...explode(':', $priorOpening));
$closeDate = $currentDate->setTime(...explode(':', $priorClosing));
$diff = $priorOpenDate->diff($closeDate);
if ($diff->d === 0 && $currentDate < $closeDate) {
//check if the closing has not occurred yet
$currentDate = $priorDate;
}
$today = $currentDate->format('l');
$start = self::setting('opening_time_' . $today);
$end = self::setting('closing_time_' . $today);
return $start . " - " . $end;
}
另外,由于只有 Mon-Thur 在午夜后营业,您可以硬编码日期以检查并根据当前时间确定选择哪一天。
本例只检查当前日期是否为Tues-Fri,当当前时间未到01:30时,将today更改为yesterday。
public static function Today() {
$currentDate = new \DateTimeImmutable;
if (in_array($currentDate->format('N'), [2, 3, 4, 5])) {
//check current time is not beyond the threshold
$closedDate = $currentDate->setTime(1, 30, 00);
if ($currentDate < $closedDate) {
//change the date to display to day prior
$currentDate = $currentDate->sub(new \DateInterval('P1D'));
}
}
$today = $currentDate->format('l');
$start = self::setting('opening_time_' . $today); // Select value from settings table
$end = self::setting('closing_time_' . $today); // Select value from settings table
return $start . " - " . $end;
}