问题描述
我想创建一个DateInterval值为负的DatePeriod对象.
I want to create a DatePeriod object with a negative DateInterval.
这将创建一个DatePeriod,年份从今天到2016年将增加.
This creates a DatePeriod with the year increasing from today to 2016.
$this->Set('dates', new DatePeriod(new DateTime(), new DateInterval('P1Y'), new DateTime('2016-06-06')));
我想从2016年开始,并使用DateInterval的负数移动到今天的年份
I want to start at 2016, and using a negative DateInterval move towards todays year
这样的事情可能说明了我的愿望
Something like this might illustrate my desire
$this->Set('dates', new DatePeriod(new DateTime('2016-06-06'), new DateInterval('-P1Y'), new DateTime()));
我只是找不到有关DatePeriod或DateInterval的扩展信息.我发现的是DateInterval可以反转.
I just can't find any extended info on either DatePeriod or DateInterval on how to do this. All i find is that DateInterval can be inverted.
推荐答案
根据由kevinpeno在php.net的页面上于2011年3月17日07:47发表有关DateInterval :: __ construct()的评论,您无法通过构造函数直接创建否定的DateIntervals:
According to comment by kevinpeno at 17-Mar-2011 07:47 on php.net's page about DateInterval::__construct(), you cannot directly create negative DateIntervals through the constructor:
new DateInterval('-P1Y'); // Exception "Unknown or bad format (-P1Y)"
相反,您需要创建一个正间隔并将其invert
属性显式设置为1
:
Instead of this you are required to create a positive interval and explicitly set it's invert
property to 1
:
$di = new DateInterval('P1Y');
$di->invert = 1; // Proper negative date interval
我自己检查了上面的代码,它正是以这种方式工作.
Just checked the above code by myself, it's working exactly in this way.
这篇关于负日期间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!