2013-01-23 41 views
14

我了解日期期间如何工作,但有一个例外,是否有方法从日期期间找出有多少间隔?PHP DatePeriod()的迭代计数

因此,例如:

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

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

这是我想从上面的代码做什么:

echo count($period); 

基本上我想知道foreach循环将有多少时间,到头来。

回答

22

您可以使用此iterator_count功能:

echo(iterator_count($period)); 
+5

请注意,'iterator_count'内部遍历所有项目来计算它们。所以如果这段时间很长,并且反复遍历它,那么可以自己进行计数,这样会更加高效。 –

-2
class MyDatePeriod extends DatePeriod 
{ 
    public $dates; 

    public function toArray() 
    { 
     if ($this->dates === null) { 
      $this->dates = iterator_to_array($this); 
     } 

     return $this->dates; 
    } 
} 

$p = new MyDatePeriod(date_create('2008-01-01'), 
         DateInterval::createFromDateString("+2 days"), 
         date_create('2008-12-31')); 

echo count($p->toArray()) . "\n"; // 183 

echo count($p->toArray()) . "\n"; // 183 
+0

不......如果你必须用继承来解决这个问题,至少应该实现'Countable'接口,而不是像这样过于复杂的事情。但无论如何,延长DatePeriod是不好的做法。 –

+2

扩展标准库是一种不好的做法吗?所有电子产品都爆炸了。 – David

+0

是的,*扩展*类只是为了添加功能通常是一个坏主意。请参阅[组合继承](http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance)(或[这里](http://en.wikipedia.org/wiki/Composition_over_inheritance)或[这里](http://c2.com/cgi/wiki?CompositionInsteadOfInheritance)。这里一个干净的替代方案是[Decorator](http://en.wikipedia.org/wiki/Decorator_pattern),因为它可以独立地添加多个功能。但是对于这种特定的情况,这将是过度工程,'iterator_count'和'iterator_to_array'很好地完成这项工作 –

1

假设你有兴趣计数的天数只(不考虑间隔规范的) - THX @马克 - 阿梅里奥为使这起来!

另一个更明显的方法是比较两个日期并获得结果的天数。

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

务必验证您的GET变量以避免日期警告/错误。比

犹未晚从未;-)

编辑:

如果你只有你有访问周期的开始和结束期间的对象。

$numDays = $period 
    ->getEndDate() 
    ->diff($period->getStartDate()) 
    ->days; 
+0

-1;这假定'DatePeriod'具有1天'DateInterval',不一定是这种情况。 –