将分钟添加到 PHP 日期时间以计算事件的开始/结束
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13781120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add minutes to PHP Datetime to calculate start/end of event
提问by Stefano
I would like to calculate with PHP the start and end datetime of an event. I get the start of this event and the duration to add to get the end. So I tried the following code:
我想用 PHP 计算事件的开始和结束日期时间。我得到了这个事件的开始以及为结束而添加的持续时间。所以我尝试了以下代码:
$startTime = $this->getStartTime();
$endTime = $this->getStartTime();
$endTime->add(new DateInterval('PT75M'));
in this example I add 75 minutes to the start time and I calculate the end of the event. It works, however it edits also the start time. I read in the PHP docs that the ADD method edits the object which is called on but I don't understand how it could edit the startEdit variable. I don't use reference in any of the methods that I wrote in the example, neither in the getStartTime function
在本例中,我将 75 分钟添加到开始时间并计算事件的结束时间。它有效,但它也会编辑开始时间。我在 PHP 文档中读到 ADD 方法编辑被调用的对象,但我不明白它如何编辑 startEdit 变量。我没有在示例中编写的任何方法中使用引用,也没有在 getStartTime 函数中使用
回答by Benjamin Paap
You have to create a new DateTime instance for that or you will be editing your original reference to your start date DateTime object. Try something like this:
您必须为此创建一个新的 DateTime 实例,否则您将编辑对开始日期 DateTime 对象的原始引用。尝试这样的事情:
$endTime = clone $startTime;
$endTime->add(new DateInterval('PT75M'));

