php - add 3 minutes to date variable

旧时模样 提交于 2019-12-02 10:06:35

问题


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?

I tried this before:

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

but that gives the current time with 3 minutes added, it doesnt use the $date variable...

And I tried:

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

But then when I do

echo date_format($time, 'G:i');

nothing is echoed...

Any help here?


回答1:


You could just use strtotime twice:

$date = strtotime('2011-10-18T19:56:00+0200');
echo date('G:i', strtotime('+3 minutes', $date));



回答2:


Instead of

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

try (for adding 3 minutes)

$time = DateTime::createFromFormat("Y-m-d\TH:i:sO", $date);
$time->add(new DateInterval('PT3M'));

First, since you're using PHP's DateTime class, you don't need to assign the output of the add method to a variable - it will modify the DateTime you passed into the constructor. Second, if you're making modifications to time using the same class, you have to make sure there's a T before your time definition. For your example, DateInterval('P2H') is invalid - it should be DateInterval('PT2H').



来源:https://stackoverflow.com/questions/7812112/php-add-3-minutes-to-date-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!