Genius
Genius

Reputation: 13

MySQL DateTime incrase by 1 minute with PHP

I want to have DATETIME records on MySQL database increased by 1 minute In a sequential manner to end with something like:

2018-02-08 00:00:00
2018-02-08 00:01:00
2018-02-08 00:02:00
2018-02-08 00:03:00

tried to update records by doing this:

$minutes = 0;

    foreach ($rows as $row) {
        $minutes++;
        $newtimestamp = strtotime('2018-02-18 00:00 + '.$minutes.' minute');
        $updated = date('Y-m-d H:i:s', $newtimestamp);
    }

But, it's not working and I get same time for each records on MySQL.

Upvotes: 2

Views: 74

Answers (2)

Suneel Kumar
Suneel Kumar

Reputation: 1664

Here is an example :

$tableresults = array('2018-02-08 00:00:00','2018-02-08 00:00:00','2018-02-08 00:00:00','2018-02-08 00:00:00');

$i=1;

foreach($tableresults as $DateTime){
        $DateTime = date('Y-m-d H:i:s',strtotime($DateTime));
        echo $cenvertedTime = date('Y-m-d H:i:s',strtotime('+'.$i.' minutes',strtotime($DateTime)));
    $i++;
}

Upvotes: 0

gogaz
gogaz

Reputation: 2400

You can use DateTime and DateInterval objects to achieve this:

$records = array(1, 2, 3, 4, 5);

$start_time = new DateTime('2018-02-18');

foreach ($records as $record)
{
  $start_time->add(new DateInterval('PT1M')); // Add 1 minute
  echo $start_time->format('Y-m-d H:i:s');
}

Output:

2018-02-18 00:01:00
2018-02-18 00:02:00
2018-02-18 00:03:00
2018-02-18 00:04:00
2018-02-18 00:05:00

Upvotes: 3

Related Questions