php - add two hours to date variable

I want to add 3 minutes to a date/time variable I have, but I'm not sure how to do this. I made the variable from a string like this: (which is in the RFC 2822 date format btw)

$date = 2011-10-18T19:56:00+0200

I converted that string into date using this command:

$time = date_format(DateTime::createFromFormat("Y-m-d\TH:i:sO", $date), "G:i")

Now, I'd like to add 3 minutes to that variable, but I I'm not sure how. I've used the following command in my script before, but that applies to the current date/time, so I'm not sure how to use that for my time variable:

$currenttime = date('G:i', strtotime('+2 hours'));

So, how can I add three minutes to the $time variable?


Solution 1:

echo $idate="2013-09-25 09:29:44";

$effectiveDate = strtotime("+40 minutes", strtotime($idate));

echo date("Y-m-d h:i:s",$effectiveDate);

Solution 2:

Use the second parameter of strtotime to provide a reference time:

$date_rfc2822 = '2011-10-18T19:56:00+0200';
$dateTime = DateTime::createFromFormat("Y-m-d\TH:i:sO", $date_rfc2822);
echo date('G:i', strtotime('+2 hours', $dateTime->getTimestamp()));

Solution 3:

Since you're using the DateTime object already, stick with it:

$time = DateTime::createFromFormat("Y-m-d\TH:i:sO", $date);
$three_minutes = $time->add(new DateInterval('P2H'));
                                               ^^--two (2) hours (H)

Solution 4:

The format starts with the letter P, for "period." Each duration period is represented by an integer value followed by a period designator. If the duration contains time elements, that portion of the specification is preceded by the letter T.

http://www.php.net/manual/en/dateinterval.construct.php

That being said my solution to a similar problem is this:

// pretend that $date is what you got from mysql
// which is like 2013-02-12 23:08:17
echo "<br>";
echo $date;
$time = DateTime::createFromFormat("Y-m-d H:i:s", $date);
echo "<br>";
echo $time->format('H-i-s');
$time->add(new DateInterval('PT2H'));
echo "<br>";
echo $time->format('H-i-s');
// Outputs:
// 2013-02-12 23:08:17
// 23-08-17
// 01-08-17

The thing is to add P when using DateInterval class, and T before time entries. For your case you need to go with PT3M for 3 minute addition. I was trying to add 2 hours and what I did was $time->add(new DateInterval('PT2H'));.

If you would look at the interval specs:

Y   years
M   months
D   days
W   weeks. These get converted into days, so can not be combined with D.
H   hours
M   minutes
S   seconds

M for months and M for minutes. That is why there is a T in front of time.

At least that's what I want to believe... 'O_O