Liam
Liam

Reputation: 93

Time based PHP greetings

I have a simple PHP time based message script (based on the users local time). It's not working as I had imagined, not quite sure what is wrong.

I'm basically looking for these messages at these times:

  1. 3am - 6am - Message 1
  2. 6am - 12pm - Message 2
  3. 12pm - 3pm - Message 3
  4. 3pm - 6pm - Message 4
  5. 6pm - 8pm - Message 5
  6. 8pm - 10pm - Message 6
  7. 10pm -12am - Message 7
  8. 12am - 3am - Message 8

I have this code already:

    <?php

    $b = time();

    $hour = date("g", $b);
    $m    = date("A", $b);

    if ($m == "AM") {
      if ($hour == 12) {
        echo "Good Evening!";
      } elseif ($hour < 4) {
        echo "Good Evening!";
      } elseif ($hour > 3) {
        echo "Good Morning!";
      }
    }

        elseif ($m == "PM") {
      if ($hour == 12) {
        echo "Good Afternoon!";
      } elseif ($hour < 6) {
        echo "Good Afternoon!";
      } elseif ($hour > 5) {
        echo "Good Evening!";
      }
    }

    ?> 

This is okay, but it seems to be an hour ahead of what I expected, I'm assuming this is because it's reading GMT, whereas the UK is currently in BST (GMT+1). If that can't be fixed, that's not a problem as I can just adjust the hour accordingly. When I try to add the additional times I require messages for though, I have been getting some strange results. I'm new to PHP, so any help would be great.

Thanks

Upvotes: 2

Views: 3124

Answers (2)

letsjak
letsjak

Reputation: 359

Try this (from http://php.net/manual/en/function.date-default-timezone-set.php)

<?php
    date_default_timezone_set('Europe/Brussels'); //added line
    $b = time();

    $hour = date("g", $b);
    $m    = date("A", $b);

    if ($m == "AM") {
      if ($hour == 12) {
        echo "Good Evening!";
      } elseif ($hour < 4) {
        echo "Good Evening!";
      } elseif ($hour > 3) {
        echo "Good Morning!";
      }
    }

        elseif ($m == "PM") {
      if ($hour == 12) {
        echo "Good Afternoon!";
      } elseif ($hour < 6) {
        echo "Good Afternoon!";
      } elseif ($hour > 5) {
        echo "Good Evening!";
      }
    }

    ?> 

Upvotes: 2

Cheruvian
Cheruvian

Reputation: 5877

You are going to want to set your default time zone. Here is a handy script straight from the PHP docs...

date_default_timezone_set('America/Los_Angeles');

$script_tz = date_default_timezone_get();

if (strcmp($script_tz, ini_get('date.timezone'))){
    echo 'Script timezone differs from ini-set timezone.';
} else {
    echo 'Script timezone and ini-set timezone match.';
}

A list of all supported time zones: http://www.php.net/manual/en/timezones.europe.php

And if i remember correctly you only need to run it once to set the time zone.

Upvotes: 3

Related Questions