Reputation: 93
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:
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
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
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