负日期间隔 [英] Negative DateInterval

查看:79
本文介绍了负日期间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个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.

推荐答案

根据

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.

这篇关于负日期间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆