php - 添加 3 分钟到日期变量
我想向已有的日期/时间变量添加 3 分钟,但我不知道如何执行此操作。我从这样的字符串创建了变量:(顺便说一句,它采用 RFC 2822 日期格式)
$date = 2011-10-18T19:56:00+0200
我使用以下命令将该字符串转换为日期:
$time = date_format(DateTime::createFromFormat("Y-m-d\TH:i:sO", $date), "G:i")
现在,我想向该变量添加 3 分钟,但我不知道怎么办。我之前在脚本中使用过以下命令,但这适用于当前日期/时间,所以我不确定如何将其用于我的时间变量:
$currenttime = date('G:i', strtotime('+2 hours'));
那么,如何向 $time 变量添加三分钟?
我之前尝试过:
$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()));
但是这给出了添加了 3 分钟的当前时间,它不使用 $date 变量...
我尝试过:
$time = DateTime::createFromFormat("Y-m-d\TH:i:sO", $date);
$time = $time->add(new DateInterval('P2H'));
但是当我
echo date_format($time, 'G:i');
什么都不做时就会回显...
这里有什么帮助吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只需使用
strtotime
两次:You could just use
strtotime
twice:而不是
尝试(添加 3 分钟)
首先,由于您使用的是 PHP 的 DateTime 类,因此您不需要将
add
方法的输出分配给变量 - 它会修改您的 DateTime传递到构造函数中。其次,如果您使用同一个类修改时间,则必须确保时间定义之前有一个T
。对于您的示例,DateInterval('P2H')
无效 - 它应该是DateInterval('PT2H')
。Instead of
try (for adding 3 minutes)
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 aT
before your time definition. For your example,DateInterval('P2H')
is invalid - it should beDateInterval('PT2H')
.