How to add +10 integer seconds to date in a loop in PHP

0

I want the loop to run 10 times, and that every loop the $tempo variable that has the date / em> minute and seconds receive +10 seconds, but in the final result does not appear in fragmented seconds, 59, I want only integers, or more specifically 00 , 10 , 20 , 30 , 40 , 50 .

The result of the variable $tempo in loop should be something like:

2001_12_15_001510
2001_12_15_001520
2001_12_15_001530
2001_12_15_001540
2001_12_15_001550
2001_12_15_001600
2001_12_15_001610
2001_12_15_001620
2001_12_15_001630
2001_12_15_001640

I could only get the seconds in integers without the loop with

if(in_array($segundos, range("00", "09"))){
    $segundos = "00";
}
    
asked by anonymous 31.03.2016 / 02:03

2 answers

1

I do not understand exactly what you're trying to do. But this code will list exactly what you want. Let me know if it's not what you need. Please post some snippets of your code so that I know what you need best.

$time = strtotime(str_replace('_', '', '2001_12_15_001510'));
for($i = 0; $i < 10; $i++){
    echo date('Y_m_d_His', $time).' - '.$time.'<br>';
    $time += 10;
}

The output looks like this

2001_12_15_001510 - 1008371710
2001_12_15_001520 - 1008371720
2001_12_15_001530 - 1008371730
2001_12_15_001540 - 1008371740
2001_12_15_001550 - 1008371750
2001_12_15_001600 - 1008371760
2001_12_15_001610 - 1008371770
2001_12_15_001620 - 1008371780
2001_12_15_001630 - 1008371790
2001_12_15_001640 - 1008371800

As you can see, you only have the seconds or date in the format you requested.

    
31.03.2016 / 04:24
1

The numbers are broken because the entry has a value that is not a multiple of ten. To fix this, you need to move to the nearest time whose seconds is a multiple of 10.

We do this with the mod operator (in PHP, % ), it takes the rest of a division. Suppose the seconds are 32, we need to get to 40 to start adding 10 to 10. You divide the 32 by 10, and take the rest of the division, which is 2. The difference between 10 and 2 (10 - 2 = 8 ) is what we need to add to get 40 (32 + 8 = 40). The complete expression is 32 + (10 - (32 % 10)) = 40

See the implementation:

// Define a zona antes de mexer com DateTime
date_default_timezone_set('America/Sao_Paulo');

// A data inicial tem que estar nesse formato (ISO 8601)
$inicial = '2012-07-08 11:14:58';

$tempo = new DateTime($inicial);

// Encontra o horário mais próximo com os segundos múltiplo de 10
$addSegundos = 10 - ($tempo->format('s') % 10);
$tempo->add(new DateInterval('PT'.$addSegundos.'S'));

for ($i = 0; $i < 10; $i++) {
    if ($i != 0)
        // Adiciona 10 segundos ao $tempo
        $tempo->add(new DateInterval('PT10S'));

    echo $tempo->format("Y_m_d_His\n");
}
    
31.03.2016 / 04:37