根据一天中的时间运行代码

时间:2011-12-28 06:12:13

标签: php date time

我需要在页面上回显一些代码或消息,具体取决于一天中的小时。就像欢迎辞,“晚安”或“下午好”

我不知道如何分组特定时间并为每个组分配消息,例如

从下午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';
}
?>

但我不知道如何传递消息的小时范围。

5 个答案:

答案 0 :(得分:31)


    <?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";
    }
    ?>

答案 1 :(得分:10)

$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?";
}

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

答案 2 :(得分:8)

我认为这个帖子可以使用一个很好的单行程序:

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

如果您先检查最高时间(晚上),则可以完全取消范围检查,并制作一个更好,更紧凑的条件语句。

答案 3 :(得分:3)

$dt = new DateTime();

$hour = $dt->format('H');

现在在您的早晨,下午,晚上或晚上检查此$hour并相应地发送消息

答案 4 :(得分:0)

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";
}
enter code here
else{
    echo "Why aren't you asleep?  Are you programming?<br>";
}

&GT;