treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Time Greeting

  • Hey there guys, I'm trying to show a time greeting on my site. The only problem is that I'd like it to display "Good Afternoon" from 12pm onwards, this doesn't seem to be working. Site link (http://hollandalekane.co.uk/)

    Code used:
    <?php 
    $b = time();
    $hour = date(\"g\",$b);
    $m = date (\"A\", $b);

    if ($m == \"AM\") { if ($hour == 12)
    { echo \"<h2 class='evening'>Good Evening!</h2>\"; }
    elseif ($hour < 4)
    { echo \"<h2 class='evening'>Good Evening!</h2>\"; }
    elseif ($hour > 3)
    { echo \"<h2 class='morning'>Good Morning!</h2>\"; }
    }

    elseif ($m == \"PM\")
    {
    if ($hour == 12)
    { echo \"<h2 class='afternoon'>Good Afternoon!</h2>\"; }
    elseif ($hour < 7)
    { echo \"<h2 class='afternoon'>Good Afternoon!</h2>\"; }
    elseif ($hour > 6)
    { echo \"<h2 class='evening'>Good Evening!</h2>\"; }
    }
    ?>
  • I've just had a look at your site and it says 'Good afternoon' for me.

    I'm in Spain and it's 16:35 here, so it seems to be working fine.
  • Is there a way to make my page display this?:

    - 12:00 AM - 12:00 PM > (Good Morning)

    - 12:00 PM - 06:00PM > (Good Afternoon)

    - 06:00 PM - 12:00 AM > (Good Evening)
  • This works for me:
    [code=php]
    <?php
        $cD 
    date("G");
        if(
    $cD <= '12'){
            echo 
    'Good Morning';
        }else if(
    $cD <= '18'){
            echo 
    'Good Afternoon';
        }else{
            echo 
    'Good Evening';
        }
    ?>
    [/code]

    But like this it will get the current server time. so if the visiter is from another GMT area then it doesn't work correctly for that visiter.
  • If you use php, you will get the server time not the person's local time (as eXo above me said). You can use javascript to get the person's local time (or atleast the time they have on their computer) and render the page from there. A quick google search can give you the function for that.

    -T
  • I agree with the two above posts, it should be generated with Javascript

    Javascript:

    window.onload = function () {
    timegreeting();
    }

    function timegreeting() {
    var now = new Date();
    var greet;
    /* If before 11:00 */
    if (now.getHours() < 11) {
    greet = \"<p>Good morning!</p>\";
    }
    /* If between 11:00 and 17:00 (5:00, all times are expressed in 24 hr time) */
    else if (now.getHours() < 17) {
    greet = \"<p>Whatever</p>\";
    }
    /* If after 17:00 */
    else {
    greet = \"<p>Good evening!</p>\";
    }
    document.getElementById(\"greeting\").innerHTML = greet;
    }


    HTML:

    <div id=\"greeting\"></div>


    I used that script a long time ago, but it seems to work well