Adding minutes to date time in PHP

Luke B picture Luke B · Nov 17, 2011 · Viewed 194.2k times · Source

I'm really stuck with adding X minutes to a datetime, after doing lots of google'ing and PHP manual reading, I don't seem to be getting anywhere.

The date time format I have is:

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

Minutes to add will just be a number between 0 and 59

I would like the output to be the same as the input format with the minutes added.

Could someone give me a working code example, as my attempts don't seem to be getting me anywhere?

Answer

Tim Cooper picture Tim Cooper · Nov 17, 2011
$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 standard for duration is a string in the form of P{y}Y{m1}M{d}DT{h}H{m2}M{s}S where the {*} parts are replaced by a number value indicating how long the duration is.

For example, P1Y2DT5S means 1 year, 2 days, and 5 seconds.

In the example above, we are providing PT5M (or 5 minutes) to the DateInterval constructor.