Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count iterations of PHP DatePeriod()

I understand how date period works with one exception, is there a way to find out from date period how many intervals there are?

So for instance:

// define the period of the range
$period = new DatePeriod($begin, $rangeType, $end);

// iterate through the dates in range
foreach ( $period as $dt ) {
}

This is what I would like to do from the above code:

echo count($period);

Basically I want to know how many time the foreach loop will end up running.

like image 321
Tom Bird Avatar asked Jan 23 '13 21:01

Tom Bird


2 Answers

You can use the iterator_count function for this:

echo(iterator_count($period));
like image 129
DiverseAndRemote.com Avatar answered Oct 23 '22 11:10

DiverseAndRemote.com


Assuming that you are interested in counting the number of days only (regardless of the interval spec) - thx @mark-amery for bringing this up!

Another more obvious approach would be to diff the 2 dates and get the number of days from the result.

$numDays = $end->diff($begin)->days;
$numDaysFormatted = $end->diff($begin)->format('%d days');

Be sure to validate your GET vars to avoid date warnings / errors.

Better late than never ;-)

EDIT:

If you only have a period object you do have access to the start and end of the period.

$numDays = $period
    ->getEndDate()
    ->diff($period->getStartDate())
    ->days;
like image 1
4levels Avatar answered Oct 23 '22 10:10

4levels