I want to create a DatePeriod object with a negative DateInterval.
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')));
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()));
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.
The span of time between a specific start date and end date.
Represents a date interval. A date interval stores either a fixed amount of time (in years, months, days, hours etc) or a relative time string in the format that DateTimeImmutable's and DateTime's constructors support.
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)"
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.
This took a little digging. The only way I was able to get a negative DateInterval
was by doing this:
$interval = DateInterval::createFromDateString('-1 day');
However, there is a catch. DatePeriod
seems to not work for negative intervals. If you set the start date to be before the end date then it doesn't contain any dates at all and if you flip so that the start date is after the end date then it looks backwards indefinitely.
You're probably going to have to restructure your code to loop through the dates using DateTime::sub
with a positive DateInterval
or DateTime::add
with the negative one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With