确定当前时间是否在当天下午5点之前


Determining whether the current time is before 5pm that day

我希望有一个循环中的代码,只有在任何一天下午5点之前才能运行。

什么代码可以做到这一点?

IF (current_time < 5:00pm) {
   // Do stuff
}

此解决方案使用了漂亮的PHP5 DateTime类,并避免了笨重的旧strtotime()函数:

$hoursNow = new DateTime()->format('H');
if($hoursNow < 17) {
    ....
}

完成任务的简单方法:

if (date('H') < 17)
{
    // DO SOMETHING
}

请记住,此日期来自服务器。因此,如果客户端在另一个时区,则可能无法按要求工作。这样做的好处是,用户不能为了欺骗网站而更改计算机日期。

如果你想用javascript(其中值将来自用户的计算机)来实现这一点,只需执行以下操作:

var today = new Date();
if (today.getHours() < 17)
{
    // DO SOMETHING
}
if(time() < strtotime('today 05:00 pm')) {
   // Do stuff
}

简而言之。。。

$t = time(); # or any other timestamp
if (date('H', $t) < 17) {
  // Do stuff
  }

适用于任何一天的

注意:请确保您的时区是正确的(在调用日期函数之前,请检查php配置或只使用date_default_timezone_set函数)