How to check if my current time is in a time interval?

4

I'd like to know if my current schedule is in an hour range.

$hora1 = "08:25:00";
$hora2 = "12:25:00";
$horaAtual = date('h:i:s');

How do I know if $horaAtual is between $hora1 and $hora2 ?

    
asked by anonymous 16.11.2015 / 05:52

3 answers

4

You can work with timestamp

$start = strtotime( date('Y-m-d' . '08:25:00') );
$end = strtotime( date('Y-m-d' . '12:25:00') );
$now = time();

if ( $start <= $now && $now <= $end ) {
    echo 'Está entre o intervalo';
}

Or work with DateTime

$start = new DateTime('04:00:00');
$end = new DateTime('06:30:00');
$now = new DateTime('now');

if ( $start <= $now && $now <= $end ) {
    echo 'Está entre o intervalo';
}
    
16.11.2015 / 08:26
1

The form I recommend is the most appropriate, using the object new DateTime() :

function checkInterval($dateInterval, $startDate, $endDate) {
   $dateInterval = new DateTime($dateInterval);
   $startDate = new DateTime($startDate);
   $endDate = new DateTime($endDate);

   $startDate->format('Y-m-d H:i:s.uO'); 
   $endDate->format('Y-m-d H:i:s.uO'); 

  return ($dateInterval->getTimestamp() >= $startDate->getTimestamp() &&
          $dateInterval->getTimestamp() <= $endDate->getTimestamp());

} 
//usando a verificação...
  if (checkInterval(date('Y-m-d H:i:s'), date('Y-m-d').' 08:25:00', date('Y-m-d').' 12:25:00')) {
       echo "Está no intervalo!";
      }; 
    
16.11.2015 / 13:07
0

Simple function using timestamp:

// Função
function intervaloEntreDatas($inicio, $fim, $agora) {
   $inicioTimestamp = strtotime($inicio);
   $fimTimestamp = strtotime($fim);
   $agoraTimestamp = strtotime($agora);
   return (($agoraTimestamp >= $inicioTimestamp) && ($agoraTimestamp <= $fimTimestamp));
}

// Parametros
$inicio = '08:25:00';
$fim = '12:25:00';
$agora = date("H:i:s");

// Chamada
if(intervaloEntreDatas($inicio,$fim,$agora)){
    echo 'Esta no Intervalo';
} else {
    echo 'Não esta no intervalo';
}
    
16.11.2015 / 11:29