php - add two hours to date variable

感情迁移 提交于 2019-11-27 09:21:30
saikat
echo $idate="2013-09-25 09:29:44";

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

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

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()));

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)

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

//set the date and time

$start = '2017-01-01 14:00:00';

//display the converted time you want to add for ex. 1 hour and 20 minutes 

echo date('Y-m-d H:i:s',strtotime('+1 hour +20 minutes',strtotime($start)));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!