Coder Perfect

In PHP, you can add minutes to a date time.

Problem

I’m having trouble adding X minutes to a datetime, and despite a lot of googling and reading the PHP documentation, I don’t seem to be going anywhere.

The date time format I have is:

2011-11-17 05:05: year-month-day hour:minute

To add minutes, simply enter a value between 0 and 59.

I’d like the output to be in the same format as the input, but with the addition of minutes.

Could someone provide me with a workable code example, as my efforts so far haven’t yielded any results?

Asked by Luke B

Solution #1

$minutes_to_add = 5;

$time = new DateTime('2011-11-17 05:05');
$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));

$stamp = $time->format('Y-m-d H:i');

The ISO 8601 duration standard is a string in the form PyYm1MdDThHm2MsS, with the * sections replaced by an integer value indicating how long the duration is.

P1Y2DT5S, for example, stands for one year, two days, and five seconds.

The DateInterval constructor is given PT5M (or 5 minutes) in the example above.

Answered by Tim Cooper

Solution #2

PHP’s DateTime class has a useful modify method which takes in easy-to-understand text.

$dateTime = new DateTime('2011-11-17 05:05');
$dateTime->modify('+5 minutes');

You may also parameterize it using string interpolation or concatenation:

$dateTime = new DateTime('2011-11-17 05:05');
$minutesToAdd = 5;
$dateTime->modify("+{$minutesToAdd} minutes");

Answered by Daniel

Solution #3

$newtimestamp = strtotime('2011-11-17 05:05 + 16 minute');
echo date('Y-m-d H:i:s', $newtimestamp);

result is

Here is a live demonstration.

If you’re not familiar with strtotime, you should go to php.net to learn more about it:-)

Answered by Nemoden

Solution #4

This is simple to perform with native functions:

strtotime('+59 minutes', strtotime('2011-11-17 05:05'));

However, Tim’s DateTime class method is one I’d advocate.

Answered by Brad

Solution #5

I’m not sure why the solution technique didn’t work for me. So, in the hopes of helping others, I’m sharing what worked for me:

$startTime = date("Y-m-d H:i:s");

//display the starting time
echo '> '.$startTime . "<br>";

//adding 2 minutes
$convertedTime = date('Y-m-d H:i:s', strtotime('+2 minutes', strtotime($startTime)));

//display the converted time
echo '> '.$convertedTime;

Answered by user3361395

Post is based on https://stackoverflow.com/questions/8169139/adding-minutes-to-date-time-in-php