PHP: check time and output appropriate greeting - php

I am writing a small php program that greets according to the time of day on the server. The rules are as follows:
Between 3:00:00 AM and 11:59:59 AM say Good morning!.
Between 12:00:00 PM and 4:59:59 PM say Good afternoon!.
Between 5:00:00 PM and 2:59:59 AM say Good evening!.
First, to simply matters, I decide to use military time. My program is as follows:
function greetingWord()
$hour = date("G");
if($hour >= 15 && $hour < 24)
{
echo "<p>Good Morning. Today is: </p>";
} else if($hour >= 12 && $hour < 17)
{
echo "<p>Good afternoon. Today is: </p>";
}
else if($hour >= 17 && $hour < 3)
{
echo "<p>Good evening. Today is: </p>";
}
}
my question regards that last else if. I suspect there is something wrong with my logic there so I'd apperciate it if someone would help me out with that final condition, the case of it being between 5pm and 2:59am.
Thank you!
DB

I think the easiest way to do it is leaving the last condition with a simple "else", so:
function greetingWord(){
$hour = date("G");
if($hour > 0 && $hour < 24){
if($hour >= 3 && $hour < 12)
{
echo "<p>Good Morning. Today is: </p>";
}else if($hour >= 12 && $hour < 17){
echo "<p>Good afternoon. Today is: </p>";
}else{
echo "<p>Good evening. Today is: </p>";
}
}
}
Hope it works.

I used ternary operators to display a part of day with a small modification of the code.
function greetingWord(int $hour): string
{
return ($hour >= 3 && $hour < 12)
? "Morning: "
: (($hour >= 12 && $hour < 17) ? "afternoon: " : "evening:");
}
foreach(range(0, 23) as $hour) {
echo "<p> Good " . greetingWord($hour) . " Today is: ". $hour ."</p>\n";
}
//or
echo "<p> Good " . greetingWord((int) date('G')) . " Today is: ". $hour ."</p>\n";

Related

Object of class DateInterval could not be converted to int

Write a program that will input your name and birthday and will display the Date
and time of your input and display also your Age.
Also the system will greet you Good Morning / Afternoon/Evening.
The system will also inform you that you are young, very young, old, or very old
condition:
if age < 15 very young
age > 15 and < 20 young
age >= 20 and < 50 old
age >= 50 very old
im stuck on the condition of the machine determining whether i'm very young, young and old
if i run this code i always get the error of DateInterval could not be converted to int i'm at a loss of what to do
if (isset($_GET['submit'])) {
$result1= $_GET['Name'];
$result2= $_GET['Bday'];
$birthDate = $result2;
$currentDate = date("d-m-Y");
$age = date_diff(date_create($birthDate), date_create($currentDate));
date_default_timezone_set("Asia/Kolkata");
$h = date('G');
if($h>=5 && $h<=11)
{
echo "Good Morning $result1 ... <br>You are ".$age->format("%y years old, %m months and");
}
else if($h>=12 && $h<=15)
{
echo "Good Afternoon $result1 ... <br>You are ".$age->format("%y years old, %m months");
}
else
{
echo "Good Evening $result1... <br>You are ".$age->format("%y years old, %m months and");
}
if ($age < 15 )
{
echo "you are very young";
}
else if($age < 50)
{
echo "you are young";
}
else if($age < 51 )
{
echo "you are old";
}
else if ($age >= 50 )
{
echo "you are very old";
}

nested ifelse not displaying the right output based on the range criteria [duplicate]

This question already exists:
nested ifelse error on values between a given range [duplicate]
Closed 3 years ago.
Right, probably an easy one, but im having a blond moment and scratching my head.
date_default_timezone_set('Europe/London');
$today = date('d-m');
if(($today >= '01-11') && ($today <= '20-11'))
{
echo "<p class='rememberance'> </p>";
}
elseif (($today >= '2-12') && ($today <= '25-12'))
{
echo "<p class='christmas'> </p>";
}
elseif (($today >= '01-01') && ($today <= '09-01'))
{
echo "<p class='new-year'> </p>";
}
elseif (($today >= '01-04') && ($today <= '19-04'))
{
echo "<p class='easter'> </p>";
}
elseif (($today >= '01-06') && ($today <= '19-07'))
{
echo "<p class='yearend'> </p>";
}
else
{
echo "<p class='normal'> </p>";
}
I have some CSS rules set to display a little image based on the banding that the php outputs, now currently it is only showing the rememberance class! Can anyone help!!? Cheers
You try to build a calculation with a string. "Lager than" or "smaller than" would not work this way. You need to remove the minus and do that stuff with integer values. Also you need to switch the month and the day for that...
Try md and then do it like
$today = date('md');
if(($today >= 1101) && ($today <= 1120))

Greeting Message Not Change PHP

I'm Write code for greeting message using php. and its correct. but not changing messages. only one message shown "Good morning". there is another way to write code for greeting message or. can i changes in my code and how to do? please help.
<?php
function greeting_msg()
{
$hour = date('h');
if ($hour >= 20) {
echo "Good Night!";
} elseif ($hour > 17) {
echo "Good Evening!";
} elseif ($hour > 11) {
echo "Good Afternoon!";
} elseif ($hour < 12) {
echo "Good Morning!";
}
}
?>
Related to the documentation of the PHP date function, your code is not correct.
date('H'); // 24 hours with leading zeros
date('h'); // 12 hours with leading zeros
date('G'); // 24 without leading zeros
So your code is ending up with values up to twelve and it 's correct, that the 'Good Morning!' message is displayed.
Next you have to check the value of your $hour variable. Just dump the value with code looking something like this ...
echo "<pre>";
var_dump($hour);
echo "</pre>";
As long as the PHP date() function is returning strings as a result of the given format, you can run into several problems.
date('h'); // could be '03' ('03' != 3)
date('H'); // could also be '03' ('03' != 3)
date('G'); // results into '3' (3 == 3)
Then look at your if/else conditions. Does the expected value fit in your conditions? Guess the value is 20.
The value 20 would fit your first three conditions. The first condition is executed and so you 'll get the expected result 'Good night!'.
Just test your code this way.
First you need to change H instead of h to get 24 hour i.e
date('H'); // 24 hours
date('h'); // 12 hours
then you need to add few more condtions to get correct messages
$hour = date('H');
if ($hour > 5 && $hour < 10) {
echo 'Good Morning';
} elseif ($hour > 11 && $hour < 17) {
echo 'Good Afternoon';
} elseif ($hour > 17 && $hour < 20) {
echo 'Good Evening';
} else {
echo 'Good Night';
}
die;
I've made small testing of your code and here is what we have
function greeting_msg($hour)
{
$hour = $hour ?: date('H');
if ($hour >= 20) {
return "Good Night!";
} elseif ($hour > 17) {
return "Good Evening!";
} elseif ($hour > 11) {
return "Good Afternoon!";
} elseif ($hour < 12) {
return "Good Morning!";
}
}
$hoursRange = range(1, 24); // contain range between 1 to 24
foreach ($hoursRange as $range) {
echo sprintf('For %d message is: %s <br>', $range, greeting_msg($range));
}
Output in your case is
For 1 message is: Good Morning!
For 2 message is: Good Morning!
For 3 message is: Good Morning!
For 4 message is: Good Morning!
For 5 message is: Good Morning!
For 6 message is: Good Morning!
For 7 message is: Good Morning!
For 8 message is: Good Morning!
For 9 message is: Good Morning!
For 10 message is: Good Morning!
For 11 message is: Good Morning!
For 12 message is: Good Afternoon!
For 13 message is: Good Afternoon!
For 14 message is: Good Afternoon!
For 15 message is: Good Afternoon!
For 16 message is: Good Afternoon!
For 17 message is: Good Afternoon!
For 18 message is: Good Evening!
For 19 message is: Good Evening!
For 20 message is: Good Night!
For 21 message is: Good Night!
For 22 message is: Good Night!
For 23 message is: Good Night!
For 24 message is: Good Night!
Which mean that your system is saying "Good morning" starting from 01:00, which isn't true. I've made some minor changed to your conditions:
function greeting_msg()
{
$hour = date('H');
if ($hour >= 20 || $hour < 5) {
return "Good Night!";
} elseif ($hour > 17) {
return "Good Evening!";
} elseif ($hour > 11) {
return "Good Afternoon!";
} else {
return "Good Morning!";
}
}
I don't know is 05:00 is Morning for somebody, but I've set it :) And now range from 20:00 to 05:00 is showing "Good Night".
Also, don't forget that server time can have different timezone from yours.
The difference between date('h') and date('H') is that one is using the 24-hour format (H) and one is using the 12-hour format (h). So, when you do date('h'), you will always get values from 0-12.
From the date manual,
| Format | Description | Values |
|--------|--------------------------------------------------|---------------|
| h | 12-hour format of an hour with leading zeros | 01 through 12 |
| H | 24-hour format of an hour with leading zeros | 00 through 23 |
This means that the behavior you are describing is correct, as date('h') will be no more than 12, and you are checking for date('h') < 12, a condition that will always be true.
Using date('H'), and some minor adjustments is shown below (we echo the result of the function, not inside it, and some logical changes to simplify readability).
function greeting_msg() {
$hour = date('H');
if ($hour > 20 || $hour < 5) {
return "Good night";
} elseif ($hour > 17) {
return "Good evening";
} elseif ($hour > 12) {
return "Good afternoon";
} else {
return "Good morning";
}
}
echo greeting_msg();
Test of all hours where we mimic the 24 hours at https://3v4l.org/B8qC0
PHP.net on date()
public function greeting_msg() {
date_default_timezone_set('Europe/Brussels');
$hour = date('H');
if ($hour >= 04 && $hour < 11) {
$greeting = "Goedenmorgen";
} elseif ($hour == 11) {
$greeting = "Goedemiddag";
} elseif ($hour >= 11 && $hour <= 17) {
$greeting = "Goedemiddag";
} elseif ($hour >= 17 && $hour <= 23) {
$greeting = "Goedenavond";
} else {
$greeting = "Goedennacht";
}
return $greeting;
}

Trying to make if, elseif, else statement for time and when to eat using military clock format

Whenever I put in the number 12 or 16, for example, it will not say "It's time for lunch" or "It's time for dinner." It will always say "It's time for breakfast"
I've tried putting quotes around the numbers, I've tried looking at my greater than, less than, etc. signs, and it looks like that is not the problem i think..
<?php
$time = 4;
if(($time >= 4) || ($time <= 11))
{
echo "It's time for breakfast";
}
elseif(($time >= 12) || ($time <= 15))
{
echo "It's time for lunch";
}
else
{
echo "It's time for dinner";
}
?>
I want it to run so when I make 4 - 11 in $time it will echo "It's time for breakfast." I want from 12 - 15 in $time to echo "It's time for lunch." All other numbers should print It's time for dinner.
You need to change your conditions. Right now, you're asking:
"If the time is greater than or equal to 4 OR time is less than or equal to 15..."
It will always be true if the time is greater than or equal to 4 OR less than or equal to 15 so the else if will never be reached. You must change to AND so both conditions must be met to stay in the if block.
<?php
$time = 16;
if(($time >= 4) && ($time <= 11))
{
echo "It's time for breakfast";
}
elseif(($time >= 12) && ($time <= 15))
{
echo "It's time for lunch";
}
else
{
echo "It's time for dinner";
}
?>
Its easy to get lost in many if ifelse else conditions. A simple way would I like to think about them is to think of them systematically, like this for example:
$time = 4;
if ( $time >= 15 || $time < 4 ) {
echo "It's time for dinner";
} elseif( $time >= 12 ) {
echo "It's time for lunch";
} elseif ( $time >= 4 ) {
echo "It's time for breakfast";
}

Pulling in data around/after midnight

Ok.. so I've created myself a messy problem.
So I have a jquery slider that shows 5 slides of content
1) -2 hours ago
2) -1 hour ago
3) (0) present
4) +1 hours
5) +2 hours
The content for each slide is decided by what time of day it is. However when it comes to trying to go back/forwards 1 to 2 hours during the run up to midnight and after midnight the whole script breaks, and kills the site.
<?php
$h = date('G', strtotime ("-2 hour")); //set variable $h to the hour of the day.
$m = date('i', strtotime ("-2 hour")); //set variable $m to the min of the hour.
$d = date('w', strtotime ("-2 hour")); //set variable $d to the day of the week.
// SATURDAY SCHEDULE
if ($d == 6 && $h >= 0 && $h < 07) $file ='earlyhours.php';
else if ($d == 6 && $h >= 07 && $h < 09) $file ='breakfast.php';
else if ($d == 6 && $h >= 09 && $h < 12) $file ='throughthemorning.php';
else if ($d == 6 && $h >= 12 && $h < 13) $file ='rewind.php';
else if ($d == 6 && $h >= 13 && $h < 17 && $m <= 30) $file ='nonstop.php';
else if ($d == 6 && $h >= 17 && $m >= 30 && $h <21) $file ='livetrend.php';
else if ($d == 6 && $h >= 17 && $m >= 35 && $h < 21) $file ='nonstop.php';
else if ($d == 6 && $h >= 21 && $h < 18) $file ='gennation.php';
else if ($d == 6 && $h >= 23) $file ='earlyhours.php';
else if ($d == 7 && $h >= 0) $file ='earlyhours.php';
require $_SERVER['DOCUMENT_ROOT'] . '/collection/profiles/' . $file . '';
?>
As you can see it figures the time and then drops the correct file in - there's five of these for everyday of the week (-2.php, -1.php, 0.php, 1.php, 2.php).
Does anybody have a solution? Ideally I need to stop the break, but I don't want my visitors to be scrolling +1 / 2 or -1 / 2 hours on for the same days rotation when it nears, and steps over midnight.
For example, right now the code is broken on -2.php until at least 2am (my timezone) so that it back track.
I've totally burnt myself out trying to figure this one out.
The problems arising from the change of day can become intractable. I'd tackle this a different way. Start by calculating the day and hour for the five periods your interested in and use DateTime to do the heavy lifting. Then, use a function to provide the schedule item for a particular day/time combination.
Here's a skeleton
<?php
date_default_timezone_set('Pacific/Auckland');
$now = new DateTime();
$oneHour = new DateInterval('PT1H');
$minusOne = (clone $now);
$minusOne->sub($oneHour);
$minusTwo = (clone $minusOne);
$minusTwo->sub($oneHour);
$plusOne = (clone $now);
$plusOne->add($oneHour);
$plusTwo = (clone $plusOne);
$plusTwo->add($oneHour);
echo returnFile($minusTwo);
echo returnFile($minusOne);
echo returnFile($now);
echo returnFile($plusOne);
echo returnFile($plusTwo);
function returnFile(DateTime $t) {
$day = $t->format('D');
$hour = $t->format('G');
// echo "Day:$day, Hour: $hour;<br>";
switch ($day) {
case 'Mon':
if ($hour<7) {
// Small hours Monday...
$filename = "smallMonday.html";
break;
}
if ($hour<12) {
// Monday morning
$filename = "morningMonday.html";
break;
}
break;
case 'Tue':
if ($hour >=23) {
// Late Tuesday
$filename = "lateTuesday.html";
}
default:
$filename = "Some other time";
}
return $filename;
}
?>
I haven't put in a complete schedule - you can work that out.
If you're using PHP 5.5 or later you can use DateTimeImmutable instead of DateTime which does away with all the cloning.
There's a fiddle here
Get rid of the leading zeros in your comparisons. Those are octal numbers and not decimals. You won't get the results you expect.
// 09 is not a valid octal number. It gets converted to zero in decimal.
else if ($d == 6 && $h >= 07 && $h < 09)
..
else if ($d == 6 && $h >= 09 && $h < 12) $file ='throughthemorning.php';

Categories