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

2022-08-30 19:22:18

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

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

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

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


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


答案 2

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

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

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


推荐