php在某两个时间之间的关系,php – 当前在两个给定时间之间的时间?

这是我的面向对象解决方案,基于PHP

DateTime class的使用(自5.2版本起可用):

class Restaurant {

private $cw;

private $times = array();

private $openings = array();

public function __construct(array $times) {

$this->times = $times;

$this->setTimes(date("w") ? "this" : "last");

//print_r($this->openings); // Debug

}

public function setTimes($cw) {

$this->cw = $cw;

foreach ($this->times as $key => $val) {

$t = array();

$buf = strtok($val, ' -,');

for ($n = 0; $buf !== FALSE; $n++) {

try {

$d = new DateTime($buf);

$d->setTimestamp(strtotime(substr($key, -3)." {$this->cw} week {$buf}"));

if ($n && ($d < $t[$n-1])) {

$d->add(new DateInterval('P1D'));

}

$t[] = $d;

} catch (Exception $e) {

break;

}

$buf = strtok(' -,');

}

if ($n % 2) {

throw new Exception("Invalid opening time: {$val}");

} else {

$this->openings[substr($key, -3)] = $t;

}

}

}

public function isOpen() {

$cw = date("w") ? "this" : "last";

if ($cw != $this->cw) {

$this->setTimes($cw);

}

$d = new DateTime('now');

foreach ($this->openings as $wd => $t) {

$n = count($t);

for ($i = 0; $i < $n; $i += 2) {

if (($d >= $t[$i]) && ($d <= $t[$i+1])) {

return(TRUE);

}

}

}

return(FALSE);

}

}

$times = array(

'opening_hours_mon' => '9am - 8pm',

'opening_hours_tue' => '9am - 2am',

'opening_hours_wed' => '8:30am - 2am',

'opening_hours_thu' => '9am - 3pm',

'opening_hours_fri' => '8:30am - 11am',

'opening_hours_sat' => '9am - 3pm, 5pm - 2am',

'opening_hours_sun' => 'closed'

);

try {

$r = new Restaurant($times);

$status = $r->isOpen() ? 'open' : 'closed';

echo "status=".$status.PHP_EOL;

} catch (Exception $e) {

echo $e->getMessage().PHP_EOL;

}

?>

您可以看到,构造函数构建一个内部窗体(DateTime对象的开放数组),然后使用isOpen方法进行简单的比较,以检查调用餐厅打开或关闭的时间。

您还会注意到,我使用DateTime:add方法来计算明天的日期,而不是在当前日期时间戳中添加86400(24 * 60 * 60),以避免DST时移的问题。

概念证明:

ini_set("date.timezone", "Europe/Rome");

echo "date.timezone = ".ini_get("date.timezone").PHP_EOL;

$d1 = strtotime("2013-10-27 00:00:00");

$d2 = strtotime("2013-10-28 00:00:00");

// Expected: 86400, Result: 90000

echo "Test #1: ".($d2 - $d1).PHP_EOL;

// Expected: 2013-10-28 00:00:00, Result: 2013-10-27 23:00:00

echo "Test #2: ".date("Y-m-d H:i:s", $d1 + 86400).PHP_EOL;

$d1 = strtotime("2014-03-30 00:00:00");

$d2 = strtotime("2014-03-31 00:00:00");

// Expected: 86400, Result: 82800

echo "Test #3: ".($d2 - $d1).PHP_EOL;

// Expected: 2014-03-30 00:00:00, Result: 2014-03-29 23:00:00

echo "Test #4: ".date("Y-m-d H:i:s", $d2 - 86400).PHP_EOL;

?>

其中给出以下结果:

date.timezone = Europe/Rome

Test #1: 90000

Test #2: 2013-10-27 23:00:00

Test #3: 82800

Test #4: 2014-03-29 23:00:00

因此,似乎有一天不总是有86400秒;每年至少不要两次

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值