Conner Burnett
Conner Burnett

Reputation: 512

PHP Date Open and Close Script

I have a task to create a script using php to display open and closed during the correct times. So far I have the time working correcty and this would be fine if the business was open during this time for 7 days a week. However the scenerio for the project is the business is open mon-fri 7:00am - 5:30 pm then open saturdays 7:00am to 1:00pm and closed sundays. I thought I could use a date function w since is displays 0-6 and call if

if($date >= 0 && $date < 6)

but that didn't work. Here is the code I have so far

<?php

date_default_timezone_set('America/Chicago');
$open = "700";
$close = "1730";
$time = date('Gi');
$day = date('w');

if ($time >= $open && $time <= $close) {
    echo "We are Open";
} else {
    echo "We are closed";
}

?>

Upvotes: 0

Views: 1659

Answers (2)

Mikhail
Mikhail

Reputation: 9007

If you're not using a database you can hardcode each day of the week in some easily parsable format:

$schedule[0] = "700-1730";
$schedule[1] = "700-1730";
$schedule[2] = "700-1730";
$schedule[3] = "700-1730";
$schedule[4] = "700-1730";

$schedule[5] = "700-1300";
$schedule[6] = "0";

$today = $schedule[date('w')];

list($open, $close) = explode('-', $schedule);

$now = (int) date('Gi');

$state = 'Open';

if ($today[0] == 0 || $now < (int) $today[0] || $now > (int) $today[1]) {
  $state = 'Closed';
}

Just wrote the code, didn't test it yet.

Good luck!

Upvotes: 1

Alex
Alex

Reputation: 146

Create DateTime objects for the open and close times. Then compare the current time as a DateTime object with those times. You can then use comparison operators. You can also then check the day and have it go in an if, elseif, and else statement for whether the day is a weekday, Saturday, or Sunday.

Upvotes: 0

Related Questions