Display text based on time of day PHP - php

I'm using the following code to show opening and closing times throughout the week however on a Tuesday the time to open is at 10:30. It seems to want to sit at 10 or 11. I've tried 10.5 in the PHP variable, but that's not making a change. Any suggestions?
<?php
date_default_timezone_set('Europe/London'); // set it to the right value
$weAreOpen = areWeOpen(date('l'), date('G'));
if($weAreOpen) {
echo 'We are open for business';
} else {
echo 'We are closed';
}
/**
* Test if we're open for business
* #param string $day - day of week (ex: Monday)
* #param string $hour - hour of day (ex: 9)
* #return bool - true if open interval
*/
function areWeOpen($day, $hour) {
$hour = (int)$hour;
switch($day) {
case 'Monday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Tuesday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Wednesday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Thursday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Friday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Saturday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Sunday':
if($hour >= 10 && $hour < 16) {
return true;
}
break;
}
return false;
}
?>

You should read up on what date('G') actually does in the PHP manual for date(). It gives you the hour in an 24 hour format. So, naturally, there can never be a .5 hour.
To check for half hours you can for example get the minutes from here, but in general there is probably a better solution than to check all parts of the clock individually, e.g. checking if the time of the day is lower or greater than something.

You just need to pass minutes as function parameter and use it in if condition like this
<?php
date_default_timezone_set('Europe/London'); // set it to the right value
$weAreOpen = areWeOpen(date('l'), date('G'), date('i'));
if($weAreOpen) {
echo 'We are open for business';
} else {
echo 'We are closed';
}
/**
* Test if we're open for business
* #param string $day - day of week (ex: Monday)
* #param string $hour - hour of day (ex: 9)
* #return bool - true if open interval
*/
function areWeOpen($day, $hour, $minutes) {
$hour = (int)$hour;
switch($day) {
case 'Monday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Tuesday':
if($hour >= 11 && $hour < 21 || ($hour == 10 && $minutes >= 30)) {
return true;
}
break;
case 'Wednesday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Thursday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Friday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Saturday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Sunday':
if($hour >= 10 && $hour < 16) {
return true;
}
break;
}
return false;
}
?>

You should also send the minutes information to your function and check with it.
$weAreOpen = areWeOpen(date('l'), date('G'), date('i'));
...
...
function areWeOpen($day, $hour, $minutes) {
...
// check the minutes value as well
...
}

You need to incorporate minutes and not only hours if you want to react on times like "10:30". Try this:
<?php
date_default_timezone_set('Europe/London'); // set it to the right value
$weAreOpen = areWeOpen(date('l'), date('G'), date('i'));
if($weAreOpen) {
echo 'We are open for business';
} else {
echo 'We are closed';
}
/**
* Test if we're open for business
* #param string $day - day of week (ex: Monday)
* #param string $hour - hour of day (ex: 9)
* #param string $minute - minute (ex: 42)
* #return bool - true if open interval
*/
function areWeOpen($day, $hour, $minute) {
switch($day) {
case 'Monday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Tuesday':
if(($hour + $minute/60) >= 10.5 && $hour < 21) {
return true;
}
break;
case 'Wednesday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Thursday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Friday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Saturday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Sunday':
if($hour >= 10 && $hour < 16) {
return true;
}
break;
}
return false;
}
?>

You cast your variable to an integer in the very first line of your function:
$hour = (int)$hour;
So any information after the hour number will be lost after that.
Removing that line would solve that.
By the way, I don't see any logic in your function that accounts for the Tuesday opening time.
You should probably decide on a format (real time or floats) first and adapt your logic accordingly. I would probably use a DateTime object to store all the information about the moment you are querying about and would give you the possibility to expand the function for holidays, etc..

I would suggest what others already have, you need to include minutes if you want to check against a half hour. Though, I would also simply the rest of the code:
<?php
$weAreOpen = areWeOpen(date('l'), date('G'), date('i'));
if($weAreOpen) {
echo 'We are open for business';
} else {
echo 'We are closed';
}
/**
* Test if we're open for business
* #param string $day - day of week (ex: Monday)
* #param string $hour - hour of day (ex: 9)
* #param int $min - Minute of the hour
* #return bool - true if open interval
*/
function areWeOpen($day, $hour, $min) {
$hour = (int)$hour;
switch($day) {
case 'Monday':
case 'Wednesday':
case 'Thursday':
case 'Friday':
case 'Saturday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Tuesday':
if(($hour >= 11 && $hour < 21) || ($min >= 30 && $hour == 10)) {
return true;
}
break;
case 'Sunday':
if($hour >= 10 && $hour < 16) {
return true;
}
break;
}
return false;
}
?>

Related

Trying to show different banner images based on server time using PHP

I have four greeting images which I intend to show based on what time user enters the site.
$morning = "img/morning.png";
$afternoon = "img/afternoon.png";
$evening = "img/evening.png";
$night = "img/night.png";
And I have some conditional statements to assign the values to $cover variable. When I tested, the conditional statement doesn't work.
date_default_timezone_set('Asia/Yangon');
$Hour = date('G');
if($Hour >= 5 && $Hour <= 11) {
$cover = $morning;
}elseif ($Hour >= 11 && $Hour <= 4) {
$cover = $afternoon;
}elseif ($Hour >= 4 && $Hour <= 9){
$cover = $evening;
}elseif ($Hour >= 9 && $Hour <= 4) {
$cover = $night;
}
Img tag
<img class="card-img-top" src="<?php echo $cover; ?>" alt="Not Available" >
if($Hour >= 0 && $Hour <= 11) {
$cover = $morning;
}
elseif ($Hour > 11 && $Hour <= 16) {
$cover = $afternoon;
}
elseif ($Hour > 16 && $Hour <= 19){
$cover = $evening;
}
else{
$cover = $night;
}
Above code will check your hours from 00:00 until 24:00 next day. I fixed your if-else statements so they make more sense in a way that there is a flow in the times.
G 24-hour format of an hour without leading zeros 0 through 23
$hour = date('H', time());
if( $hour > 6 && $hour <= 11) {
$cover = $morning;
}
else if($hour > 11 && $hour <= 16) {
$cover = $afternoon;
}
else if($hour > 16 && $hour <= 23) {
$cover = $evening;
}
else {
$cover = $night;
}
Construct an instance of date and acquire the hour from it

How to know actual working shift with php

I'm trying to identify the current work shift from 3 options (24 hour format)
First shift 06:00 to 13:59
Second shift 14:00 to 21:59
Third shift 22:00 to 05:59
I tried this, but it's not working as expected
$hour = date("0500");
$shift;
if ($hour >= 0600 && $hour <= 1359 ) {
$shift = 1;
}else if($hour >= 14 && $hour <= 2159 )
{
$shift = 2;
}else
{
$shift = 3;
}
Maybe:
$hour = data('H');
if($hour >= 6 && $hour < 14) {
$shift = 1;
} else if($hour >= 14 && $hour < 22) {
$shift = 2;
} else {
$shift = 3;
}
You could try something like this perhaps:
$hour = data('H');
switch( true ){
case ( $hour >= 6 && $hours < 14 ):$shift=1; break;
case ( $hour >=14 && $hour < 22 ):$shift=2; break;
default: $shift=3; break;
}
Put your time in quotes otherwise starting with 0 makes it an octal number
Also stick with one format if you are going to be comparing
$hour = date("Hi", strtotime("05:00"));
$shift;
if ($hour >= "0600" && $hour <= "1359" ) {
$shift = 1;
}else if($hour >= "1400" && $hour <= "2159" ) {
$shift = 2;
}else {
$shift = 3;
}

eliminate weekends (sunday) by a php script

I am trying to count number of working days available for particular hours set. here i just need to exclude Sundays by the following php script. if this script find a Sunday this should increase the count. its working but,
This script is capable to exclude first 'Sunday' but not the 'second' and 'third'.
kindly give me a solution to correct this
function testRange() {
$phone_Quantity = 0;
$phone_Quantity = $_POST['phoneQuantity'];
if ($phone_Quantity > 0 && $phone_Quantity <= 300) {
return 300;
} elseif ($phone_Quantity >= 301 && $phone_Quantity <= 600) {
return 600;
} elseif ($phone_Quantity >= 601 && $phone_Quantity <= 900) {
return 900;
} elseif ($phone_Quantity >= 601 && $phone_Quantity <= 1200) {
return 1200;
} elseif ($phone_Quantity >= 1201 && $phone_Quantity <= 1500) {
return 1500;
} elseif ($phone_Quantity >= 1501 && $phone_Quantity <= 1800) {
return 1800;
}
}
echo testRange();
$query_to_get_hours = "SELECT
cdma_filtering_target_hours.Target_hours
FROM
cdma_filtering_target_hours
WHERE
cdma_filtering_target_hours.No_of_units='" . testRange() . "'
";
$query_to_get_hours_query = $system->prepareSelectQuery($query_to_get_hours);
foreach ($query_to_get_hours_query as $THours) {
$targeted_hours = $THours['Target_hours'];
}
$hid = 24; // Hours in a day - could be 24, 48, etc
$days = round($targeted_hours / $hid);
for ($xdays = 0; $xdays < $days; $xdays++) {
if (date('l', strtotime(date('y-m-d', strtotime("+$xdays days")))) == 'Sunday') {
$days++;
break;
}
}
Why do you converting +$xdays string representation twice?
If you comment your if statement and add next line
echo date('l', strtotime("+$xdays days"));
you can clearly see that it works.

php echo Open or Closed business hours depending on date or date

I have reviewed the q/a's on here and have not found an answer for what I am trying to do. I want to put a $variable inside of an array, kind of like an echo.
Here is an example:
$days = '"12/25","12/26"';
return array($days);
I am wanting the above to look like this when the PHP page loads, so that the variable loads/echos inside the array
$days = '"12/25","12/26"';
return array("12/25","12/26")
Here is my entire code, it echos Business hours Open or Closed. As you can see, I want to be able to change the holidays dates from the top of the code to prevent from going to bottom of the page inside the code to change it. I have tried, ($holidays) (holidays) ('$holidays')
<?php
$holidays = '"12/25","12/26"';
date_default_timezone_set('America/New_York');
// Runs the function
echo time_str();
function time_str() {
if(IsHoliday())
{
return ClosedHoliday();
}
$dow = date('D'); // Your "now" parameter is implied
// Time in HHMM
$hm = (int)date("Gi");
switch(strtolower($dow)){
case 'mon': //MONDAY adjust hours - can adjust for lunch if needed
if ($hm >= 830 && $hm < 1700) return Open();
else return Closed();
break;
case 'tue': //TUESDAY adjust hours
if ($hm >= 830 && $hm < 1700) return Open();
else return Closed();
break;
case 'wed': //WEDNESDAY adjust hours
if ($hm >= 830 && $hm < 1700) return Open();
else return Closed();
break;
case 'thu': //THURSDAY adjust hours
if ($hm >= 830 && $hm < 1700) return Open();
else return Closed();
break;
case 'fri': //FRIDAY adjust hours
if ($hm >= 830 && $hm < 1700) return Open();
else return Closed();
break;
case 'sat': //Saturday adjust hours
return Closed();
break;
case 'sun': //Saturday adjust hours
return Closed();
break;
}
}
// List of holidays
function HolidayList()
{
// Format: 05/11 (if year/month/day comma seperated for days)
return array($holidays);
}
// Function to check if today is a holiday
function IsHoliday()
{
// Retrieves the list of holidays
$holidayList = HolidayList();
// Checks if the date is in the holidaylist - remove Y/ if Holidays are same day each year
if(in_array(date("m/d"),$holidayList))
{
return true;
}else
{
return false;
}
}
// Returns the data when open
function Open()
{
return 'We are Open';
}
// Return the data when closed
function Closed()
{
return 'We are Closed';
}
// Returns the data when closed due to holiday
function ClosedHoliday()
{
return 'Closed for Holidays';
}
// Returns if closed for lunch
// if not using hours like Monday - remove all this
// and make 'mon' case hours look like 'tue' case hours
function Lunch()
{
return 'Closed for Lunch';
}
?>
To help Clarify, This is the actual working code. It displays "We are Open","We are Closed","Closed for Holidays" depending on the day of the week, time, and holidays. "Closed for Holidays" is only displayed if it is one of those days listed in Holidays. It works fine, but I was trying to change it so that if I wanted to add more days to the Holidays schedule, I could easily do it at the top of the page code, rather than scrolling down. I know lazy, but it was for production purposes.
<?php
date_default_timezone_set('America/New_York');
// Runs the function
echo time_str();
function time_str() {
if(IsHoliday())
{
return ClosedHoliday();
}
$dow = date('D'); // Your "now" parameter is implied
// Time in HHMM
$hm = (int)date("Gi");
switch(strtolower($dow)){
case 'mon': //MONDAY adjust hours - can adjust for lunch if needed
if ($hm >= 830 && $hm < 1700) return Open();
else return Closed();
break;
case 'tue': //TUESDAY adjust hours
if ($hm >= 830 && $hm < 1700) return Open();
else return Closed();
break;
case 'wed': //WEDNESDAY adjust hours
if ($hm >= 830 && $hm < 1700) return Open();
else return Closed();
break;
case 'thu': //THURSDAY adjust hours
if ($hm >= 830 && $hm < 1700) return Open();
else return Closed();
break;
case 'fri': //FRIDAY adjust hours
if ($hm >= 830 && $hm < 1700) return Open();
else return Closed();
break;
case 'sat': //Saturday adjust hours
return Closed();
break;
case 'sun': //Saturday adjust hours
return Closed();
break;
}
}
// List of holidays
function HolidayList()
{
// Format: 05/11 (if year/month/day comma seperated for days)
return array("12/25","12/26");
}
// Function to check if today is a holiday
function IsHoliday()
{
// Retrieves the list of holidays
$holidayList = HolidayList();
// Checks if the date is in the holidaylist - remove Y/ if Holidays are same day each year
if(in_array(date("m/d"),$holidayList))
{
return true;
}else
{
return false;
}
}
// Returns the data when open
function Open()
{
return 'We are Open';
}
// Return the data when closed
function Closed()
{
return 'We are Closed';
}
// Returns the data when closed due to holiday
function ClosedHoliday()
{
return 'Closed for Holidays';
}
// Returns if closed for lunch
// if not using hours like Monday - remove all this
// and make 'mon' case hours look like 'tue' case hours
function Lunch()
{
return 'Closed for Lunch';
}
?>
$holidays is a "convenience" variable that you are treating as a constant. After the first assignment, it is never changed within your code.
In your previous implementation, $holidays was useful as a string. With your new multi-day holidays requirement, it will be more useful to initialise it as an array of "m/d" strings.
<?php
$holidays = array("12/25", "12/26");
//...
?>
After making the above change, your HolidayList() function becomes redundant, so remove it. Also $holidaysList becomes redundant, so replace every instance of it with $holidays (there is only one instance).
I assume you wanto convert the string into array.
you can first explode them using comma as delimiter, then remove the double quote from the value and put in the days array variable.
<?php
$string = '"12/25","12/26"';
$tmps = explode(',', $string);
foreach($tmps as $tmp)
{
$days[] = str_replace("\"","", $tmp);
}
print_r($days);

PHP if specific business day of week and time echo

The following code works to echo "Open" or "Closed" if time is between 8:15am and 5:30pm. I am trying to make it day specific. How can I incorporate format character 'D' as example, Mon hours 8:15am - 5:30pm .. echo "Open", Sat hours 8:15am - 1:00pm "Open". I want to be able to control echo of Open/Closed by each day and time.
current working code for hours only
<?php
date_default_timezone_set('America/New_York');
$hour = (int) date('Hi');
$open = "yah hoo, we are open";
$closed = "by golly, im closed";
if ($hour >= 0815 && $hour <=1735) {
// between 8:15am and 5:35pm
echo "$open";
} else {
echo "$closed";
}
?>
example of what I am trying to do:
$hour = (int) date('D Hi');
if ($hours >= 0815 && $hour <=1735 && $hour === 'Mon')
{ echo "$open"; }
else { echo "$closed"; }
if ($hours >= 0815 && $hour <=1300 && $hour === 'Sat')
{ echo "$open"; }
else { echo "$closed"; }
another example per The One and Only's answer which looks close to what I am looking for, but this also does not work
<?php
$openDaysArray = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat','Sun');
$thisDate = date('D Hi');
$explode = explode(" ", $thisDate);
$day = $explode[0];
$time = $explode[1];
if (in_array($day, $openDaysArray))
if ($time < 815 || $time > 1730 && $day === 'Mon');
if ($time < 815 || $time > 1730 && $day === 'Tue');
if ($time < 815 || $time > 1730 && $day === 'Wed');
if ($time < 815 || $time > 1730 && $day === 'Thu');
if ($time < 815 || $time > 1730 && $day === 'Fri');
if ($time < 815 || $time > 1730 && $day === 'Sat');
if ($time < 815 || $time > 1730 && $day === 'Sun');
{echo 'Open';}
else {echo 'Closed';}
?>
I'd handle it this way. Set up an array of all your open times. If you know you're closed on Saturday and Sunday, there's really no need to proceed with with checking times at that point, so kill the process there first. Then simply find out what day of the week it is, look up the corresponding opening and closing times in your $hours array, create actual DateTime objects to compare (rather than integers). Then just return the appropriate message.
function getStatus() {
$hours = array(
'Mon' => ['open'=>'08:15', 'close'=>'17:35'],
'Tue' => ['open'=>'08:15', 'close'=>'17:35'],
'Wed' => ['open'=>'08:15', 'close'=>'17:35'],
'Thu' => ['open'=>'08:15', 'close'=>'22:35'],
'Fri' => ['open'=>'08:15', 'close'=>'17:35']
);
$now = new DateTime();
$day = date("D");
if ($day == "Sat" || $day == "Sun") {
return "Sorry we're closed on weekends'.";
}
$openingTime = new DateTime();
$closingTime = new DateTime();
$oArray = explode(":",$hours[$day]['open']);
$cArray = explode(":",$hours[$day]['close']);
$openingTime->setTime($oArray[0],$oArray[1]);
$closingTime->setTime($cArray[0],$cArray[1]);
if ($now >= $openingTime && $now < $closingTime) {
return "Hey We're Open!";
}
return "Sorry folks, park's closed. The moose out front should have told ya.";
}
echo getStatus();
Use a switch statement:
$thisDate = date('D Hi');
$hoursOfOpArray = array("Mon_Open" => "815", "Mon_Close" => "1730", "Tue_Open" => "815", "Tue_Close" => "1730"); //repeat for all days too fill this array
$explode = explode(" ", $thisDate);
$day = $explode[0];
$time = (int)$explode[1];
switch($day) {
case "Sun":
$status = "Closed";
break;
case "Mon":
$status = ($time < $hoursOfOpArray[$day . "_Open"] || $time > $hoursOfOpArray[$day . "_Close"]) ? "Closed" : "Open";
break;
//same as Monday case for all other days
}
echo $status;
This should also work:
echo ($day === 'Sun' || ($time < $hoursOfOpArray[$day . "_Open"]) || ($time > $hoursOfOpArray[$day . "_Close"])) ? "Closed" : "Open";
$o = ['Mon' => [815, 1735], /*and all other days*/'Sat' => [815, 1300]];
echo (date('Hi')>=$o[date('D')][0] && date('Hi')<=$o[date('D')][1]) ? "open": "closed";
Done! And dont ask.
This one works, added remarks to explain as much as possible.
<?php
date_default_timezone_set('America/New_York');
// Runs the function
echo time_str();
function time_str() {
if(IsHoliday())
{
return ClosedHoliday();
}
$dow = date('D'); // Your "now" parameter is implied
// Time in HHMM
$hm = (int)date("Gi");
switch(strtolower($dow)){
case 'mon': //MONDAY adjust hours - can adjust for lunch if needed
if ($hm >= 0 && $hm < 830) return Closed();
if ($hm >= 830 && $hm < 1200) return Open();
if ($hm >= 1200 && $hm < 1300) return Lunch();
if ($hm >= 1300 && $hm < 1730) return Open();
if ($hm >= 1730 && $hm < 2359) return Closed();
break;
case 'tue': //TUESDAY adjust hours
if ($hm >= 830 && $hm < 1730) return Open();
else return Closed();
break;
case 'wed': //WEDNESDAY adjust hours
if ($hm >= 830 && $hm < 1730) return Open();
else return Closed();
break;
case 'thu': //THURSDAY adjust hours
if ($hm >= 830 && $hm < 1730) return Open();
else return Closed();
break;
case 'fri': //FRIDAY adjust hours
if ($hm >= 830 && $hm < 1730) return Open();
else return Closed();
break;
case 'sat': //Saturday adjust hours
return Closed();
break;
case 'sun': //Saturday adjust hours
return Closed();
break;
}
}
// List of holidays
function HolidayList()
{
// Format: 2009/05/11 (year/month/day comma seperated for days)
return array("2016/11/24","2016/12/25");
}
// Function to check if today is a holiday
function IsHoliday()
{
// Retrieves the list of holidays
$holidayList = HolidayList();
// Checks if the date is in the holidaylist - remove Y/ if Holidays are same day each year
if(in_array(date("Y/m/d"),$holidayList))
{
return true;
}else
{
return false;
}
}
// Returns the data when open
function Open()
{
return 'Yes we are Open';
}
// Return the data when closed
function Closed()
{
return 'Sorry We are Closed';
}
// Returns the data when closed due to holiday
function ClosedHoliday()
{
return 'Closed for the Holiday';
}
// Returns if closed for lunch
// if not using hours like Monday - remove all this
// and make 'mon' case hours look like 'tue' case hours
function Lunch()
{
return 'Closed for Lunch';
}
?>

Categories