How to check if my current time is in an hour interval?

Asked

Viewed 4,049 times

5

I would like to know if my current schedule is in an hour interval.

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

How to know if $horaAtual is among $hora1 and $hora2?

3 answers

5

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';
}

1

The form I recommend and is the most indicated, 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!";
      }; 

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';
}
  • I need to adapt it to make sure that the time worked (input and output) is between a pre-set standard interval. For example, if he entered at 08:00 and left at 17:00 this within the standard of entry 08:00 and exit 18:00

Browser other questions tagged

You are not signed in. Login or sign up in order to post.