PHP Date Open and Close Script - php

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";
}
?>

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!

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.

Related

Multiple Operators in PHP If Statement

Just wanted to double check and make sure my line of thinking is correct. This hook runs every 48 hours, so I need to check if an event is happening today or tomorrow.
$now = date('Y/m/d');
$today = explode("/", $now);
The event start date has the same format, but the value varies, and is stored the same way.
if ( $today[1] == $eventDate[1] &&
(intval($today[2]) == (intval($eventDate[2]-1)) || (intval($today[2]) == intval($eventDate[2])-2))) {
//run code
}
In my opinion, you should consider to work with DateTime objects :
$today = new \DateTime();
$eventDateTime = \DateTime::createFromFormat('Y/m/d', $eventDate);
if ($today->format('d-m-Y') === $eventDateTime->format('d-m-Y')) {
...
}
If you want to check that an event is happening today or tomorrow, you could do like this :
$start = new \DateTime();
$start->setTime(0,0,0);
$end = new \DateTime();
$end->add(new \DateInterval('P1D'));
$end->setTime(23,59,59);
$eventDateTime = \DateTime::createFromFormat('Y/m/d', $eventDate);
if ($eventDateTime >= $start && $eventDateTime <= $end) {
...
}
This way you check if a date is in a certain period. Here I added 1 day to the current date but you can adapt the code and set more than 1 day if you want.

PHP script to show when a store is open

I'm trying to build a PHP script so that when a store is opened it will show the words "is now open" and when it's closed it'll show "is now closed" based on timezone and hours. I can't seem to get this to work, I found this script but it doesn't work properly.. It should work on the dutch timezone.. +1 Amsterdam.. Can anyone aid me?
I'd appreciate the help!
SCRIPT:
<?php
$schedule[0] = "700-1730";
$schedule[1] = "700-1730";
$schedule[2] = "700-1730";
$schedule[3] = "700-1730";
$schedule[4] = "10:00-17:30";
$schedule[5] = "700-1300";
$schedule[6] = "0";
$today = $schedule[date('w')];
list($open, $close) = explode('-', $schedule);
$now = (int) date('Gi');
$state = 'is geopend.';
if ($today[0] == 0 || $now < (int) $today[0] || $now > (int) $today[1]) {
$state = 'is gesloten.';
}
?>
<?php echo $state;?>
The colon is causing a bit of a problem so you can remove it with a quick str_replace();
Instead of $schedule you want to explode(); $today once you have made it.
<?php
$schedule[0] = "700-1730";
$schedule[1] = "700-1730";
$schedule[2] = "700-1730";
$schedule[3] = "700-1730";
$schedule[4] = "10:00-17:30";
$schedule[5] = "700-1300";
$schedule[6] = "0";
$today = $schedule[date('w')];
$now = (int) date('Gi');
list($open, $close) = explode('-', $today);
// get rid of colon if you have used one
$open = (int) str_replace(':', '', $open);
$close = (int) str_replace(':', '', $close);
$state = ' is geopend.';
if ($today[0] == 0 || $now < $open || $now > $close){
$state = ' is gesloten.';
}
?>
Depending on the setup of your server, if you don't want to dynamically reset timezone in your ini settings, you could add 100 per hour you want to adjust by, so if you have hours time difference in your database you could make a variable $time_difference * 100 and add it to or subtract it from $now = (int) date('Gi'); so, for example $now = (int) date('Gi') + 700; would give you European Central Time when your server time is based on New York time or $now = (int) date('Gi') + $time_difference * 100; could be used to adjust it dynamically. (You would need to account for daylight saving time though!)
Time reference for the right way to set timezones: PHP date(); with timezone?
In case you wanted to play with using the user's own timezone to display your opening times and adjust accordingly for a bit of fun - may not be advisable for a live project as there seem to be few totally reliable ways. Determine a User's Timezone
Please note that the numbers for days work from 0 for Sunday to 6 for Saturday http://php.net/manual/en/function.date.php

Check if todays date is between two other dates [duplicate]

This question already has answers here:
Check if something is between two values?
(5 answers)
Closed 5 months ago.
I am trying to check if todays date is between START and STOP date of a period, Winter, summer, spring etc..
and if the todays date is between, lets say.. the winter period, it will set the $season variable to which period it is.
But for the moment it just gives me "01/01", i don't understand why..
Thanks for help! :)
$season = date("d-m");
$season = date("d-m", strtotime($season));
$startSummer = date("01-06");
$endSummer = date("31-08");
$startAutum = date("01-09");
$endAutum = date("30-11");
$startSpring = date("01-03");
$endSpring = date("31-05");
$startWinter = date("01-12");
$endWinter = date("28-02");
// start and stop, periods
// $startYear = date("d-m", strtotime($startYear)); $endYear = date("d-m", strtotime($endYear));
$startSummer = date("d-m", strtotime($startSummer)); $endSummer = date("d-m", strtotime($endSummer));
$startAutum = date("d-m", strtotime($startAutum)); $endAutum = date("d-m", strtotime($endAutum));
$startSpring = date("d-m", strtotime($startSpring)); $endSpring = date("d-m", strtotime($endSpring));
$startWinter = date("d-m", strtotime($startWinter)); $endWinter = date("d-m", strtotime($endWinter));
if(($season > $startSummer) && ($season < $endSummer)){
$season = "Sommar";
}else if(($season > $startAutum) && ($season < $endAutum)){
$season = "Höst";
}else if(($season > $startSpring) && ($season < $endSpring)){
$season = "Vår";
}else if(($season > $startWinter) && ($season < $endWinter)){
$season = "Vinter";
}
You can stick with timestamps. Don't convert back to dates. You are making invalid comparisons such as the assumption that 30-01 is less than 28-02. The computer will compare the very first 3 to the 2 and tell you that 30-01 is CORRECTLY greater than 28-02. So...
$startSummer = mktime(0,0,0, 6, 1, 2000); // The year doesn't matter according to your code
$endSummer = mktime(0,0,0, 8, 31, 2000);
Now, is some date between those? Assume I am checking $month and $day...
$myday = mktime(0,0,0, $month, $day, 2000);
if($myday>=$startSummer && $myday<=$endSummer) $season = "Summer";
If you use DateTime object—which is by far the best approach—you are able to compare these with the regular comparators, e.g.:
$date1 = new DateTime('today');
$date2 = new DateTime('2014-04-04');
if ($date1 < $date2) echo 'Past';
else if ($date1 == $date2) echo 'Present';
else echo 'Future';
See documentation: http://php.net/manual/en/datetime.diff.php#example-2368
Remember that a variable can be overwritten - just as the year progresses through the seasons, your variable can as well - as long as we do it in order we'll end up on the correct one. This means we only have to test if our date is after the date that a season changes.
// Since we're testing today's date
// we use the current year timestamps
$year = date('Y');
$startSpring = strtotime("$year-03-01");
$startSummer = strtotime("$year-06-01");
$startAutum = strtotime("$year-09-01");
$startWinter = strtotime("$year-12-01");
$today = time();
// The year starts with Winter
$season = 'Winter';
if($today > $startSpring) $season = 'Spring'; // Past the 1st day of spring?
if($today > $startSummer) $season = 'Summer'; // Etc...
if($today > $startAutumn) $season = 'Autumn';
if($today > $startWinter) $season = 'Winter';
echo 'It is currently '.$season;
Here's the same logic cleaned up in a pretty function that will check any date for you and return the season:
// Accepts an optional unix timestamp
// Uses the current date by default
function getSeason($test_date=FALSE){
$test_date = $test_date ? $test_date : time();
// Use the year of the date we're testing
$year = date('Y', $test_date);
// The year starts with Winter
$season = 'Winter';
if($test_date > strtotime("$year-03-01")) $season = 'Spring'; // Past the 1st day of spring?
if($test_date > strtotime("$year-06-01")) $season = 'Summer'; // Etc...
if($test_date > strtotime("$year-09-01")) $season = 'Autumn';
if($test_date > strtotime("$year-12-01")) $season = 'Winter';
return $season;
}

Get time before noon

I am practicing with dates in php. I a bit of a newbie so bear my ignorance
I am trying to see when a time is before noon.
So I have a variable coming in with this format 2014-03-07 13:28:00.000
I get the time like this
$submissonTime = date('H:i:s', strtotime($value['job_submission_date']));
then I want to set another variable as $noon and i am doing this:
$noon = date('H:i:s', '12:00:00.000');
However the value of noon is 12:00:12
what i want to do is basically:
if($submissionTime <= $noon){
//do my stuff
}
NB I want to enter the if statement when even when it is 12:00:00 and stop entering when it is 12:00:01
Any help please?
Try
$noon = date('Y-m-d 12:00:00'); // today noon with date
$submissonTime = date('Y-m-d H:i:s', strtotime($value['job_submission_date']));
if(strtotime($submissonTime) <= strtotime($noon)){
//do my stuff
}
if you want to compare only time use both format
$noon = date('12:00:00');
$submissonTime = date('H:i:s', strtotime($value['job_submission_date']));
if (date("A") == "AM")
{
// AM-Code
} else {
// PM-Code
}
Why don't you go with only one string of code getting the hour?
$Hour = date("G"); //24-hour format of an hour without leading zeros
if($Hour < 12) {
// do the code
}
Or in your case
$Hour = date("G", strtotime($value['job_submission_date']));
update
If you need 12:00:00 and not 12:00:01 and later on, you will need to define minutes and seconds:
$Hour = date("G"); //24-hour format of an hour without leading zeros
$Minute = intval(date("i")); // will give minutes without leading zeroes
$Second = intval(date("s"));
if(($Hour < 12) || ($Hour == 12 && $Minute == 0 && Second == 0)) {
// do the code
}

Next business day of given date in PHP

Does anyone have a PHP snippet to calculate the next business day for a given date?
How does, for example, YYYY-MM-DD need to be converted to find out the next business day?
Example:
For 03.04.2011 (DD-MM-YYYY) the next business day is 04.04.2011.
For 08.04.2011 the next business day is 11.04.2011.
This is the variable containing the date I need to know the next business day for
$cubeTime['time'];
Variable contains: 2011-04-01
result of the snippet should be: 2011-04-04
Next Weekday
This finds the next weekday from a specific date (not including Saturday or Sunday):
echo date('Y-m-d', strtotime('2011-04-05 +1 Weekday'));
You could also do it with a date variable of course:
$myDate = '2011-04-05';
echo date('Y-m-d', strtotime($myDate . ' +1 Weekday'));
UPDATE: Or, if you have access to PHP's DateTime class (very likely):
$date = new DateTime('2018-01-27');
$date->modify('+7 weekday');
echo $date->format('Y-m-d');
Want to Skip Holidays?:
Although the original poster mentioned "I don't need to consider holidays", if you DO happen to want to ignore holidays, just remember - "Holidays" is just an array of whatever dates you don't want to include and differs by country, region, company, person...etc.
Simply put the above code into a function that excludes/loops past the dates you don't want included. Something like this:
$tmpDate = '2015-06-22';
$holidays = ['2015-07-04', '2015-10-31', '2015-12-25'];
$i = 1;
$nextBusinessDay = date('Y-m-d', strtotime($tmpDate . ' +' . $i . ' Weekday'));
while (in_array($nextBusinessDay, $holidays)) {
$i++;
$nextBusinessDay = date('Y-m-d', strtotime($tmpDate . ' +' . $i . ' Weekday'));
}
I'm sure the above code can be simplified or shortened if you want. I tried to write it in an easy-to-understand way.
For UK holidays you can use
https://www.gov.uk/bank-holidays#england-and-wales
The ICS format data is easy to parse. My suggestion is...
# $date must be in YYYY-MM-DD format
# You can pass in either an array of holidays in YYYYMMDD format
# OR a URL for a .ics file containing holidays
# this defaults to the UK government holiday data for England and Wales
function addBusinessDays($date,$numDays=1,$holidays='') {
if ($holidays==='') $holidays = 'https://www.gov.uk/bank-holidays/england-and-wales.ics';
if (!is_array($holidays)) {
$ch = curl_init($holidays);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$ics = curl_exec($ch);
curl_close($ch);
$ics = explode("\n",$ics);
$ics = preg_grep('/^DTSTART;/',$ics);
$holidays = preg_replace('/^DTSTART;VALUE=DATE:(\\d{4})(\\d{2})(\\d{2}).*/s','$1-$2-$3',$ics);
}
$addDay = 0;
while ($numDays--) {
while (true) {
$addDay++;
$newDate = date('Y-m-d', strtotime("$date +$addDay Days"));
$newDayOfWeek = date('w', strtotime($newDate));
if ( $newDayOfWeek>0 && $newDayOfWeek<6 && !in_array($newDate,$holidays)) break;
}
}
return $newDate;
}
function next_business_day($date) {
$add_day = 0;
do {
$add_day++;
$new_date = date('Y-m-d', strtotime("$date +$add_day Days"));
$new_day_of_week = date('w', strtotime($new_date));
} while($new_day_of_week == 6 || $new_day_of_week == 0);
return $new_date;
}
This function should ignore weekends (6 = Saturday and 0 = Sunday).
This function will calculate the business day in the future or past. Arguments are number of days, forward (1) or backwards(0), and a date. If no date is supplied todays date will be used:
// returned $date Y/m/d
function work_days_from_date($days, $forward, $date=NULL)
{
if(!$date)
{
$date = date('Y-m-d'); // if no date given, use todays date
}
while ($days != 0)
{
$forward == 1 ? $day = strtotime($date.' +1 day') : $day = strtotime($date.' -1 day');
$date = date('Y-m-d',$day);
if( date('N', strtotime($date)) <= 5) // if it's a weekday
{
$days--;
}
}
return $date;
}
What you need to do is:
Convert the provided date into a timestamp.
Use this along with the or w or N formatters for PHP's date command to tell you what day of the week it is.
If it isn't a "business day", you can then increment the timestamp by a day (86400 seconds) and check again until you hit a business day.
N.B.: For this is really work, you'd also need to exclude any bank or public holidays, etc.
I stumbled apon this thread when I was working on a Danish website where I needed to code a "Next day delivery" PHP script.
Here is what I came up with (This will display the name of the next working day in Danish, and the next working + 1 if current time is more than a given limit)
$day["Mon"] = "Mandag";
$day["Tue"] = "Tirsdag";
$day["Wed"] = "Onsdag";
$day["Thu"] = "Torsdag";
$day["Fri"] = "Fredag";
$day["Sat"] = "Lørdag";
$day["Sun"] = "Søndag";
date_default_timezone_set('Europe/Copenhagen');
$date = date('l');
$checkTime = '1400';
$date2 = date(strtotime($date.' +1 Weekday'));
if( date( 'Hi' ) >= $checkTime) {
$date2 = date(strtotime($date.' +2 Weekday'));
}
if (date('l') == 'Saturday'){
$date2 = date(strtotime($date.' +2 Weekday'));
}
if (date('l') == 'Sunday') {
$date2 = date(strtotime($date.' +2 Weekday'));
}
echo '<p>Næste levering: <span>'.$day[date("D", $date2)].'</span></p>';
As you can see in the sample code $checkTime is where I set the time limit which determines if the next day delivery will be +1 working day or +2 working days.
'1400' = 14:00 hours
I know that the if statements can be made more compressed, but I show my code for people to easily understand the way it works.
I hope someone out there can use this little snippet.
Here is the best way to get business days (Mon-Fri) in PHP.
function days()
{
$week=array();
$weekday=["Monday","Tuesday","Wednesday","Thursday","Friday"];
foreach ($weekday as $key => $value)
{
$sort=$value." this week";
$day=date('D', strtotime($sort));
$date=date('d', strtotime($sort));
$year=date('Y-m-d', strtotime($sort));
$weeks['day']= $day;
$weeks['date']= $date;
$weeks['year']= $year;
$week[]=$weeks;
}
return $week;
}
Hope this will help you guys.
Thanks,.
See the example below:
$startDate = new DateTime( '2013-04-01' ); //intialize start date
$endDate = new DateTime( '2013-04-30' ); //initialize end date
$holiday = array('2013-04-11','2013-04-25'); //this is assumed list of holiday
$interval = new DateInterval('P1D'); // set the interval as 1 day
$daterange = new DatePeriod($startDate, $interval ,$endDate);
foreach($daterange as $date){
if($date->format("N") <6 AND !in_array($date->format("Y-m-d"),$holiday))
$result[] = $date->format("Y-m-d");
}
echo "<pre>";print_r($result);
For more info: http://goo.gl/YOsfPX
You could do something like this.
/**
* #param string $date
* #param DateTimeZone|null|null $DateTimeZone
* #return \NavigableDate\NavigableDateInterface
*/
function getNextBusinessDay(string $date, ? DateTimeZone $DateTimeZone = null):\NavigableDate\NavigableDateInterface
{
$Date = \NavigableDate\NavigableDateFacade::create($date, $DateTimeZone);
$NextDay = $Date->nextDay();
while(true)
{
$nextDayIndexInTheWeek = (int) $NextDay->format('N');
// check if the day is between Monday and Friday. In DateTime class php, Monday is 1 and Friday is 5
if ($nextDayIndexInTheWeek >= 1 && $nextDayIndexInTheWeek <= 5)
{
break;
}
$NextDay = $NextDay->nextDay();
}
return $NextDay;
}
$date = '2017-02-24';
$NextBussinessDay = getNextBusinessDay($date);
var_dump($NextBussinessDay->format('Y-m-d'));
Output:
string(10) "2017-02-27"
\NavigableDate\NavigableDateFacade::create($date, $DateTimeZone), is provided by php library available at https://packagist.org/packages/ishworkh/navigable-date. You need to first include this library in your project with composer or direct download.
I used below methods in PHP, strtotime() does not work specially in leap year February month.
public static function nextWorkingDay($date, $addDays = 1)
{
if (strlen(trim($date)) <= 10) {
$date = trim($date)." 09:00:00";
}
$date = new DateTime($date);
//Add days
$date->add(new DateInterval('P'.$addDays.'D'));
while ($date->format('N') >= 5)
{
$date->add(new DateInterval('P1D'));
}
return $date->format('Y-m-d H:i:s');
}
This solution for 5 working days (you can change if you required for 6 or 4 days working). if you want to exclude more days like holidays then just check another condition in while loop.
//
while ($date->format('N') >= 5 && !in_array($date->format('Y-m-d'), self::holidayArray()))

Categories