【问题标题】:If time is bigger than and lower than如果时间大于和小于
【发布时间】:2015-01-03 18:11:47
【问题描述】:

我想知道如何使用php来询问时间是否大于

08:30

低于

21:15

如果我使用:

<?php

if ( (date("H")>8&&date("i")>30) && (date("H")<21&&date("i")<25) ) {
echo 'This website is closed from 08:30 - 21:25. Sorry for the Inconvenience.';
exit;

}

?>

这不是一个准确的说法,因为即使时间大于 8 且小于 21,这里也有一个分钟的验证...

【问题讨论】:

  • 为什么不简化为if ((date('Hi') &gt; 830) &amp;&amp; (date('Hi') &lt; 2125))
  • @Mark Ba​​ker :) 太简单了!

标签: php time timestamp minute


【解决方案1】:

您可以获得日期/时间和日期部分的条带。该时间可以与其他时间值进行比较。在下面的代码中,我计算了当前时间从午夜开始的秒数,8:30 和 21:15,然后if 变得非常简单:

define('SecondsPerDay', 86400);
define('SecondsPerHour', 3600);
define('SecondsPerMinute', 60);

$time = time () % SecondsPerDay;

$from = 8 * SecondsPerHour + 30 * SecondsPerMinute;
$to = 21 * SecondsPerHour + 15 * SecondsPerMinute;

if ($time >= $from && $time < $to) {
  echo 'This website is closed from 08:30 - 21:25. Sorry for the Inconvenience.';
  exit;
}

【讨论】:

  • 您能详细解释一下这些数字吗? 21*3600? 15*60?为什么* 3600?为什么*60?看了又看,我看不见
  • 一切都以秒为单位,因此每天 86400 秒,每小时 3600 秒,每分钟 60 秒。所有计算都只讨论 1 天,因此使用模数将时间保持在 24 小时范围内,并且通过执行 8*seconds_per_hour + 30*seconds_per_minute 将 8:30 转换为秒。我会更新代码。
  • 这很聪明。我喜欢这个
【解决方案2】:
$startTime = '08:30';
$endTime = '21:15';
$time = new DateTime($startTime);
$time1 =  date_format($time, 'H:i'); 
$time = new DateTime($endTime);
$time2 =  date_format($time, 'H:i');
"Today is " . $current =date("H:i") . "<br>";
if ($current > $time1 && $current < $time2)
{
echo 'This website is closed from 08:30 - 21:25. Sorry for the Inconvenience.';
}else{

echo "It's open";
}

REFERENCE

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    相关资源
    最近更新 更多