【问题标题】:run code depending on the time of day根据一天中的时间运行代码
【发布时间】:2012-01-28 23:09:28
【问题描述】:

我需要根据一天中的时间在页面上回显一些代码或消息。就像欢迎信息、“晚上好”或“下午好”

我不知道将某些时间分组并为每个组分配一条消息,例如

从下午 1:00:00 到下午 4:00:00 =“下午好”,从 4:00:01 到 8:00:00 =“晚上好”

到目前为止我有:

<?php
date_default_timezone_set('Ireland/Dublin');
$date = date('h:i:s A', time());
if ($date < 05:00:00 AM){
echo 'good morning';
}
?>

但我不知道如何通过时间范围和消息。

【问题讨论】:

    标签: php date time


    【解决方案1】:
    <?php /* This sets the $time variable to the current hour in the 24 hour clock format */ $time = date("H"); /* Set the $timezone variable to become the current timezone */ $timezone = date("e"); /* If the time is less than 1200 hours, show good morning */ if ($time < "12") { echo "Good morning"; } else /* If the time is grater than or equal to 1200 hours, but less than 1700 hours, so good afternoon */ if ($time >= "12" && $time < "17") { echo "Good afternoon"; } else /* Should the time be between or equal to 1700 and 1900 hours, show good evening */ if ($time >= "17" && $time < "19") { echo "Good evening"; } else /* Finally, show good night if the time is greater than or equal to 1900 hours */ if ($time >= "19") { echo "Good night"; } ?>

    【讨论】:

    • $timezone 变量的用途是什么?它没有在下面的代码中使用它的初始化 ;)
    【解决方案2】:

    我认为这个线程可以使用一个不错的单行:

    $hour = date('H');
    $dayTerm = ($hour > 17) ? "Evening" : (($hour > 12) ? "Afternoon" : "Morning");
    echo "Good " . $dayTerm;
    

    如果您首先检查最高小时(晚上),您可以完全消除范围检查,并制作一个漂亮、更紧凑的条件语句。

    【讨论】:

      【解决方案3】:
      $hour = date('H', time());
      
      if( $hour > 6 && $hour <= 11) {
        echo "Good Morning";
      }
      else if($hour > 11 && $hour <= 16) {
        echo "Good Afternoon";
      }
      else if($hour > 16 && $hour <= 23) {
        echo "Good Evening";
      }
      else {
        echo "Why aren't you asleep?  Are you programming?";
      }
      

      ...应该让你开始(时区不敏感)。

      【讨论】:

      • 下午应该在 11 到 16 小时之间,不是吗?
      【解决方案4】:
      $dt = new DateTime();
      
      $hour = $dt->format('H');
      

      现在在您的早上、下午、晚上或晚上范围内检查此$hour 并相应地给出消息

      【讨论】:

        【解决方案5】:
        date_default_timezone_set('Asia/Dhaka');
        $time=date('Hi'); 
        
        if (($time >= "0600") && ($time <= "1200")) {
          echo "Good Morning";
        } 
        
        elseif (($time >= "1201") && ($time <= "1600")) {
          echo "Good Afternoon";
        }
        
        elseif (($time >= "1601") && ($time <= "2100")) {
          echo "Good Evening";
        }
        
        elseif (($time >= "2101") && ($time <= "2400")) {
          echo "Good Night";
        }
        else{
          echo "Why aren't you asleep?  Are you programming?<br>";
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-09-25
          • 2011-06-21
          • 2013-04-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-14
          相关资源
          最近更新 更多