run code depending on the time of day

2019-02-01 12:25发布

I need to echo some code or message on a page depending on the hour of the day. Just like a welcome message, "good evening", or "good afternoon"

I don't know hot to group certain hours and assign a message to each group like

from 1:00:00 pm to 4:00:00pm = "good afternoon" and from 4:00:01 to 8:00:00 = "good evening"

so far I have :

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

But I don't know how to pass the hours range an the messages.

标签: php date time
5条回答
别忘想泡老子
2楼-- · 2019-02-01 12:27
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>";
}

?>

查看更多
该账号已被封号
3楼-- · 2019-02-01 12:35
$dt = new DateTime();

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

now check this $hour in your morning , afternoon , evening or night range and accordingly give the message

查看更多
Explosion°爆炸
4楼-- · 2019-02-01 12:37

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

查看更多
一夜七次
5楼-- · 2019-02-01 12:42

I thought this thread could use a nice one-liner:

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

If you check the highest hour first (evening), you can eliminate the range checks completely, and make a nice, more compact conditional statement.

查看更多
唯我独甜
6楼-- · 2019-02-01 12:52
$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?";
}

...should get you started (timezone insensitive).

查看更多
登录 后发表回答