Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative DateInterval

Tags:

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.

like image 440
user798584 Avatar asked Jun 14 '11 22:06

user798584


People also ask

What is Dateinterval?

The span of time between a specific start date and end date.

What is Dateinterval in PHP?

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.


2 Answers

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.

like image 88
hijarian Avatar answered Sep 28 '22 13:09

hijarian


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.

like image 25
Andrew Curioso Avatar answered Sep 28 '22 12:09

Andrew Curioso