2011-12-28 20 views
11

我需要根據當天的小時在頁面上回顯一些代碼或消息。就像一個值得歡迎的消息,「晚上好」或「下午好」根據一天中的時間運行代碼

我不知道燙組的某些時段和下午一點00分00秒分配一個消息給每個組像

到下午四點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'; 
} 
?> 

但我不知道如何通過小時範圍的消息。

回答

29
 

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

$ timezone變量的用途是什麼?它在初始化下面的代碼中沒有使用;) – 2017-07-31 16:02:46

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

...應該讓你開始(時區不敏感)。

+0

下午應該是11個16 ** **小時之間,是嗎? – zerkms 2011-12-28 06:20:19

+0

@zerkms - 當你說得對。修好了,謝謝! – Ben 2011-12-28 06:21:20

2
$dt = new DateTime(); 

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

現在在你的早晨,下午,傍晚或晚上範圍檢查這個$hour並相應地給予消息

4

我想這個線程可以用一個漂亮的一行:

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

如果您先檢查最早的小時(晚上),則可以完全消除範圍檢查,並製作一個更好,更緊湊的條件語句。

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

?>