Avatar of purestealth
purestealth
 asked on

Help Detecting Day And Time Between 2 Date/Time Ranges

I need to be able to detect after hour's conditions from some PHP Code.  After hours would be considered as Mon-Fri 17:00-8:59 such that any inquires sent during that time PHP knows its after hours and can do its After Hours stuff....

I have a function which can accept a time range in 24HR Format such as "17:00-8:59", or "12:33-15:55" etc etc etc...  The function currently works perfectly when the start time is less than the end time.  So "8:59-17:00" works, but "17:00-8:59" does not work.

My function needs to return a boolean indicating if the "Current Time" is between the time ranges.  The day of the week calculation is handled separately from this function so all this function below needs to care about is if the current time is in the range specified.

I have my code like this.

      function MatchTimeRange($theTime)
      {
                  // We have a time range
                  $timeParts = explode("-",$theTime);
                  $timeStart = $timeParts[0];
                  $timeEnd = $timeParts[1];
      
                  $t=time(0);
                  if ($timeStart > $timeEnd)
                  {
                        // ------------------ THIS IS THE PART THAT DOES NOT WORK ----------------------------------------------
                        return ($t<=strtotime($timeEnd)&&$t<=strtotime($timeStart))?true:false;
                  }
                  else
                  {
                        return ($t>=strtotime($timeStart)&&$t<=strtotime($timeEnd))?true:false;
                  }
            }

The problem happens when the Start time is greater than the End time (numerically).  This would happen because the end time is the next day.  However I still need the function to return true because even though its may be the next day, the current time is still in range to be considered after hours......... therefore the office is still closed and after hours logic must still prevail.

Can anyone assist with this?
PHPAlgorithms

Avatar of undefined
Last Comment
nacker2000

8/22/2022 - Mon
nacker2000

Hi,

How about this. It's a bit of a modification on what you had, but the function simply works out whether NOW is Mon-Fri between 17:00 and 8:59 and if it is then AfterHours will return true, otherwise it will return false.
<?php
	 function AfterHours(){
		$day = strtolower(date('D'));
		$time = (int)date('Gi');
 
		/* check its Mon-Fri */
		if($day!='sat'&&$day!='sun'){
			/* check time */
			if($time<=859||$time>=1700){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	
	/* check for after hours */
	if(AfterHours()){
		print('It is after hours');
	}else{
		print('It is not after hours');
	}
?>

Open in new window

nacker2000

Hi,

In case you need to be able to pass a range then I have modified it to accept a range:
<?php
	 function AfterHours($range){
		$day = strtolower(date('D'));
		$time = (int)date('Gi');
		$range = explode('-', str_replace(':', '', $range));
 
		/* check its Mon-Fri */
		if($day!='sat'&&$day!='sun'){
			/* check time */
			if($range[0]<$range[1]){
				if($time>=$range[0]&&$time<=$range[1]){
					return true;
				}else{
					return false;
				}
			}else{
				if($time<=$range[0]||$time>=$range[1]){
					return true;
				}else{
					return false;
				}
			}
		}else{
			return false;
		}
	}
	
	/* check for after hours */
	if(AfterHours('17:00-8:59')){
		print('It is after hours');
	}else{
		print('It is not after hours');
	}
?>

Open in new window

nacker2000

Hi,

There was a small bug in my code. Use this instead:
<?php
	 function AfterHours($range){
		$day = strtolower(date('D'));
		$time = (int)date('Gi');
		$range = explode('-', str_replace(':', '', $range));
 
		/* check its Mon-Fri */
		if($day!='sat'&&$day!='sun'){
			/* check time */
			if($range[0]<=$range[1]){
				if($time>=$range[0]&&$time<=$range[1]){
					return true;
				}else{
					return false;
				}
			}else{
				if($time<=$range[1]||$time>=$range[0]){
					return true;
				}else{
					return false;
				}
			}
		}else{
			return false;
		}
	}
	
	/* check for after hours */
	if(AfterHours('17:00-08:59')){
		print('It is after hours');
	}else{
		print('It is not after hours');
	}
?>

Open in new window

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
nacker2000

Oh and if you just want to use your code then this should now work... lol
<?php
	function MatchTimeRange($theTime)
	{
		// We have a time range
		$timeParts = explode('-', str_replace(':', '', $theTime));
		$timeStart = $timeParts[0];
		$timeEnd = $timeParts[1];
      
		$t = (int)date('Gi');
		if($timeStart <= $timeEnd)
		{
			// ------------------ THIS IS THE PART THAT DOES NOT WORK ----------------------------------------------
			return ($t>=strtotime($timeEnd)&&$t<=strtotime($timeStart))?true:false;
		}
		else
		{
			return ($t<=strtotime($timeEnd)||$t>=strtotime($timeStart))?true:false;
		}
	}
	
	/* check for after hours */
	if(MatchTimeRange('17:00-08:59')){
		print('It is after hours');
	}else{
		print('It is not after hours');
	}
?>

Open in new window

nacker2000

LOL... ok lets try this one more time... This code should now work, soz :)
<?php
	function MatchTimeRange($theTime)
	{
		// We have a time range
		$timeParts = explode('-', str_replace(':', '', $theTime));
		$timeStart = $timeParts[0];
		$timeEnd = $timeParts[1];
      
		$t = (int)date('Gi');
		if($timeStart <= $timeEnd)
		{
			return ($t>=strtotime($timeStart)&&$t<=strtotime($timeEnd))?true:false;
		}
		else
		{
			return ($t<=strtotime($timeEnd)||$t>=strtotime($timeStart))?true:false;
		}
	}
	
	/* check for after hours */
	if(MatchTimeRange('17:00-08:59')){
		print('It is after hours');
	}else{
		print('It is not after hours');
	}
?>

Open in new window

purestealth

ASKER
LOL - thanks for all the code :)

For some strange reason I was not being notified of your posts.  Suspecting something strange I refreshed this page and vola here were you posts :)

I am going to try this code out and post back with results. :)

Thanks in advance.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
purestealth

ASKER
Hi There

Ok I tested the code and it seems to get the job done.  However I did modify the code to make it more efficient.  Your solution was clever by striping out the ":" in the time format we end up with just an integer number which is great because it makes it simple to do greater-than / less-than comparisons.  Naturally this would only work with times that are in 24HR format.

Since we have striped out the ":" there is really no need to call strtotime() around each argument in the IF/ELSE branch of the logic, its ends up being a waste of CPU time and is really not necessary.  I have removed that and spaced out the code a bit more to make it more readable but looks like your solution works great.

Please copy this code and paste it back under your name so that I can accept it as the solution and award you the points.

Thanks again :)
function MatchTimeRange($theTime)
{
	// We have a time range
	$timeParts = explode('-', str_replace(':', '', $theTime));
	$timeStart = $timeParts[0];
	$timeEnd = $timeParts[1];
	$t = (int)date('Gi');
	if ( $timeStart <= $timeEnd )
	{
		return ( ($t>=$timeStart) && ($t<=$timeEnd) )?true:false;
	}
	else
	{
		return ( ($t<=$timeEnd) || ($t>=$timeStart) )?true:false;
	}
}

Open in new window

ASKER CERTIFIED SOLUTION
nacker2000

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.