View Tutorial Metadata Edit Content Revision History Add to Watchlist Add New Tutorial How to check if a time is inside a time interval using PHP

How to check if a time is inside a time interval using PHP

There are scripts where you need to check if a certain time (hour and minute) is inside a time frame (for example the opening hours of a shop).

Using the function below you can check this easily. You just need to provide it the next parameters :

  • $h,$m - the hour and minute of the time you want to check
  • $h1,$m1 - the hour and minute of the lower endpoint of the timeframe
  • $h2,$m2 - the hour and minute of the upper endpoint of the timeframe

and it will return true (if our time is in the timeframe) or false.

It can check for time frames that cross midnight too (for example, a restaurant that open at 11:00 and close at 02:00 in the morning).

//H:M = the time you want to check
//H1:M1 = lower part of the interval
//H2:M2 = higher part of the interval
function timeInInterval($h,$m,$h1,$m1,$h2,$m2){
	//filter the parameters
	$h = intval($h);
	$m = intval($m);
	$h1 = intval($h1);
	$m1 = intval($m1);
	$h2 = intval($h2);
	$m2 = intval($m2);
	//cases like 00:00 - 14:00
	if ($h1 < $h2){
		if (($h < $h1) || ($h > $h2)){
			return false;
		} else if (($h == $h1) || ($h == $h2)) {
			if ($h == $h1){
				if ($m < $m1){
					return false;
				}
			} else {
				if ($m > $m2){
					return false;
				}
			}
		}
	}
	//cases like 12:00 - 12:30 and 12:30-12:00
	if ($h1 == $h2){
		if ($m1 > $m2){
			//split it into 2 intervals 
			//12:30-12:00 => 12:30-23:59 and 00:00-12:00
			$tmp1 = timeInInterval($h,$m,$h1,$m1,23,59);
			$tmp2 = timeInInterval($h,$m,0,0,$h2,$m2);
			if (($tmp1 == 0) && ($tmp2 == 0)){
				return false;
			}
		} else {
			if ($h != $h2){
				return false;
			} else if (($m > $m2) || ($m < $m1)) {
				return false;
			}
		}
	}
	//cases like 08:00 - 01:00
	if ($h1 > $h2){
		//split it into 2 intervals : 08:00 - 23:59 and 00:00-01:00
		$tmp1 = timeInInterval($h,$m,$h1,$m1,23,59);
		$tmp2 = timeInInterval($h,$m,0,0,$h2,$m2);
		if (($tmp1 == 0) && ($tmp2 == 0)){
			return false;
		}
	}
	return true;
}

Only plain text supported.

Optional

Required - will be kept private

Optional

 
 

Rating: (2+, 0-) In: PHP 5