PHP Time of Day Script

One very cool way of taking advantage of PHP’s powerful language is to make a determination as to what time of the day it is, and making a decision based on that information. For example, we want to detect the server’s current time and display a message that says either good morning, good afternoon or good evening.

There’s a handy PHP function called date that we can use. We can assign a variable called $current_time, to the server’s current time.

$current_time = date(G);

Next, let’s display the logic.

if ($current_time >= 0 && $current_time < 12) { echo 'Good Morning';}
if ($current_time >= 12 && $current_time < 18) { echo 'Good Afternoon';}
if ($current_time >= 18 && $current_time < 24) { echo 'Good Evening';}

You can also display images based on time of day.

if ($current_time >= 18 && $current_time < 24) { echo<img src=”sample.jpg” />;}

4 thoughts on “PHP Time of Day Script

  1. You need to replace the OR with AND in you if statements to make them mutually exclusive.

    This way it prints out:
    “Good Morning Good Afternoon Good Evening” if for example the current time is “6”

      1. No, what I meant was that your logic will print out all 3 if say the time is 6, because it will match all the 3 conditions with the OR.
        Just test it with 6. In the first case it obviously matches, in the second it also matches because 6 is less than 18 and since it’s an OR condition it becomes true and prints the second one which it shouldn’t. Also 6 is less than 24 in the 3rd statement so that prints as well.

  2. I should run the script at least once before posting. I posted the correction. I’m now using && (AND) instead of || (OR) operator. Thanks for pointing it out.

Comments are closed.