Creating an object of class DateTime
is the easiest way to manipulate dates in your application.
When we have two objects of class DateTime
we can compare them with the diff()
method that returns a DateInterval
object and represents the difference between the two dates, which we can return according to the desired format using the date_format ()
function.
These are the concepts applied in the script to achieve the expected result. The code is well commented and there will be no difficulty in locating each concept above applied to the code.
//Array com os horarios que possam ser imprimidos
$hora = array('13:55:40','13:56:40','13:58:41','13:59:40','14:01:00','14:02:00','14:04:40',
'14:05:00','14:07:10','14:08:00','14:10:23', '14:11:23','14:13:39','14:14:23','14:16:39',
'14:17:23','14:19:13','14:20:23','14:22:40', '14:21:23','14:25:07', '14:26:23', '14:55:40');
//Intervalo que o usuario escolherá entre 3, 15, 30 ou 60
$interval = 15;
//valor de base o primeiro valor do array.
$val1 = $hora[0];
print $val1;
for ($i=0;$i<(count($hora)-1);$i++) {
$val2 = $hora[$i+1];
//Instanciando objetos DateTime
$datetime1 = new DateTime($val1);
$datetime2 = new DateTime($val2);
//Retorna a diferença entre dois objetos DateTime.
$intervalo = $datetime1->diff($datetime2);
//Retorna a dìferença de acordo com um formato informado, neste caso minutos
$result = $intervalo->format('%i');
//imprime o valor cuja diferença é dada por $interval
if($result == ($interval-1) || $result == ($interval)){
print ", ".$val2;
//atribui o valor encontrado $val2 em $val1 para buscar
//próxima diferença $interval a partir deste
$val1 = $val2;
}
}
NOTE: Note that the difference between 13:55:40, 14:10:23, is 14 minutos e 43 segundos
and not 15 minutes why the condition if($result == ($interval-1) || $result == ($interval)){
was imposed, that is = 14 or = 15
Ideone - $ interval = 15
Ideone - $ interval = 3
Another way to get the same result, regardless of the seconds, is:
//Array com os horarios que possam ser imprimidos
$hora = array('13:55:40','13:56:40','13:58:41','13:59:40','14:01:00','14:02:00','14:04:40',
'14:05:00','14:07:10','14:08:00','14:10:23','14:11:23','14:13:39','14:14:23','14:16:39',
'14:17:23','14:19:13','14:20:23','14:22:40', '14:21:23','14:25:07', '14:26:23', '14:55:40');
//Intervalo que o usuario escolherį entre 3, 15, 30 ou 60
$interval = 3;
$val1 = $hora[0];
print $val1;
//formata para am/pm sem segundos
$val1P = date( 'g:i a', strtotime($val1) );
for ($i=0;$i<(count($hora)-1);$i++) {
$val2 = $hora[$i+1];
//formata para am/pm sem segundos
$val2P = date( 'g:i a', strtotime($val2) );
$datetime1 = new DateTime($val1P);
$datetime2 = new DateTime($val2P);
$intervalo = $datetime1->diff($datetime2);
$result = $intervalo->format('%i');
if($result == $interval){
print ", ".$val2;
$val1P = $val2P;
}
}
Ideone - $ interval = 3