[英]Count iterations of 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
循環最終會運行多少次。
您可以使用iterator_count
函數:
echo(iterator_count($period));
假設您只想計算天數(無論間隔規格如何) - thx @ mark-amery將其提升!
另一個更明顯的方法是區分2個日期並從結果中獲取天數。
$numDays = $end->diff($begin)->days;
$numDaysFormatted = $end->diff($begin)->format('%d days');
請務必驗證您的GET變量以避免日期警告/錯誤。
遲到總比不到好 ;-)
編輯:
如果您只有一個句點對象,則可以訪問句點的開頭和結尾。
$numDays = $period
->getEndDate()
->diff($period->getStartDate())
->days;
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.