Skip to content
Advertisement

How can I divide a date range by number of months?

My dilemma is that if I request more than 6 months or so ( I do not know the approximate number ) from my webservices ( which gets called via JS ), I get nothing back. In other words, I have to limit it to 6 months.

So let’s consider this scenario:

JavaScript

I need to split this up by 6 months in order to make 2 distinct web servicerequests so that each call requests 6 months.

So with $a and $b, I need to split these up into as many date ranges as possible when taking the amount of months total divided by 6.

The first date range I need is from June 1, 2011 to November 31, 2011. The second date range I need is from December 1, 2011 to July 1, 2012.

The idea I had in mind was finding the number of months, then if it was greater than the limit variable 6, do a loop and increment the initial date by 6 months per loop.

Pseudo-code ( I actually initially wrote it in JS but figured it’d be easier to do in PHP because I wouldn’t have to deal with multiple asynchronous request behaviour ):

JavaScript

Does anyone know of a succinct way of doing this? Can anyone spot any programmatic flaws in this?

Advertisement

Answer

Try:

JavaScript

…where $fetchLimit in fetchAll() is any duration string parseable by strtotime(). You could then keep appending the output of each fetchChunk() to an initially blank variable which is later returned by fetchAll().

This example fetches two six-month “chunks”, as expected. Changing $b to one day later adds a third chunk containing only that extra day:

JavaScript

Of course, PHP 5.3 has somewhat more elegant time functions like DateTime::diff, but the code above should work fine in PHP 5.2.x.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement