How do you get points of interest between two moments in time?

4

Consider that there are two moments in time, represented in the standard format (HH: mm: ss).

And consider that a point of interest is any time that is represented by at most two different digits (eg: 12:12:11 or 15:15:51)

If I wanted to go from one moment to the next telling the points of interest that exist between them, how would I implement this in PHP?

I thought of nesting three loops for one to count the hours, one to count the minutes and another to count the seconds.

Ex:

    $S = '12:12:00';
    $T = '12:12:15';
    $arrS = explode(':', $S);
    $arrT = explode(':', $T);

    //Horas do primeiro momento.
    $Sh = $arrS[0];
    //Minutos do primeiro momento.
    $Sm = $arrS[1];
    //Segundos do primeiro momento.
    $Ss = $arrS[2];

    //Horas do segundo momento.
    $Th = $arrT[0];
    //Minutos do segundo momento.
    $Tm = $arrT[1];
    //Segundos do segundo momento.
    $Ts = $arrT[2];

    for($i = $Sh; $i <= $Th; $i++){
      //Conta as horas
      for($j = $Sm; $j <= $Tm; $j++){
       //Conta os minutos
        for($k = $Ss; $k <= $Ts; $k++){
         //Conta os segundos
        }
      }
    }

But I confess that from here I do not know what else to do: /

Does anyone have any ideas?

    
asked by anonymous 05.11.2015 / 12:58

1 answer

3

PHP (> = 5.3.0) provides some time-handling classes that can help: DateTime and DateInterval .

<?php
function pontosInteresseIntervalo($inicio, $fim) {
    $dateInicio = new DateTime($inicio);
    $dateFim = new DateTime($fim);
    $segundo = new DateInterval('PT1S');
    // enquanto a diferença for positiva
    while ($dateInicio->diff($dateFim)->format('%R') === '+') {
        // conta - count
        // digitos distintos - array_unique
        // convertidos em string - str_split
        // do tempo sem os pontos - $inicio->format
        if (count(array_unique(str_split($dateInicio->format('His')))) <= 2) {
            // se tem 2 digitos distintos ou menos, exibe
            var_dump($dateInicio->format('H:i:s'));
        }
        $dateInicio->add($segundo); // incrementa 1 segundo
    }
}

pontosInteresseIntervalo('19:00:00', '20:00:00');

References about the formats used (in the order they appear):

You can also do this in a simplified way with strtotime() (without version restriction):

<?php
function pontosInteresseIntervalo($inicio, $fim) {
    $timeInicio = strtotime($inicio);
    $timeFim = strtotime($fim);
    while ($timeFim - $timeInicio > 0) { // enquanto a diferenca for positiva
        if (count(array_unique(str_split(date('His', $timeInicio)))) <= 2) {
            var_dump(date('H:i:s', $timeInicio));
        }
        $timeInicio += 1; // incrementa 1 segundo
    }
}
    
05.11.2015 / 14:39