X
X
XenK2016-05-24 14:31:13
PHP
XenK, 2016-05-24 14:31:13

Add a second to a date?

There is a start date, for example 24-05-16 . You need to loop the total amount of time over several days, with seconds. That is, to make it look like this:

24-05-16 | 00:00:01
24-05-16 | 00:00:02
24-05-16 | 00:00:03
...
24-05-16 | 16:12:59
...
25-05-16 | 00:00:01
...

What is the best way to do it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
Cat Anton, 2016-05-24
@XenK

<?php

$interval = new DateInterval('PT1S'); 
$start = new Datetime('2016-05-24 00:00:01');
 
$period = new DatePeriod($start, $interval, 3 * 24 * 60 * 60);
foreach ($period as $date) { 
    echo $date->format('d-m-y | H:i:s') . PHP_EOL; 
}

If you want to be smarter, scoring the fact that there are not always 24 hours in a day, then you can do this:
<?php

$interval = new DateInterval('P1D'); 
$start = new Datetime('2016-05-24');
 
$period = new DatePeriod($start, $interval, 3);
foreach ($period as $date) {
    $day = $date->format('d-m-y');
    for ($H = 0; $H < 24; $H++) {
        for ($i = 0; $i < 60; $i++) {
            for ($s = 0; $s < 60; $s++) {
                echo sprintf('%s | %02d:%02d:%02d', $day, $H, $i, $s) . PHP_EOL; 
            }
        }
    }
}

php.net/manual/ru/dateperiod.construct.php Programmers'
misconceptions about time

A
Alexey, 2016-05-24
@alsopub

The easiest:

for (...) {
  for (...) {
    for (...) {
      echo(...);
    }
  }
}

You can also try:
for ($i=0; $i<60*60*24; $i++) {
  echo(date('H:i:s', $i)."<br>\n");
}

L
lnked, 2016-05-24
@lnked

$time = '24-05-16';
$count_day = 2;
$sec_in_one_day = 60 * 60 * 24;

if (function_exists('strtotime'))
{
    $timestamp = strtotime($time);
}
else
{
    $a = strptime($time, '%d.%m.%Y');
    $timestamp = mktime($a['tm_hour'], $a['tm_min'], $a['tm_sec'], $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900);
}

$timestamp_end = $timestamp + $count_day * $sec_in_one_day;

for ($i = $timestamp; $i <= $timestamp_end; $i++) {
    echo date('d-m-y | h:i:s', $i), '<br>';
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question