我試圖確定兩個日期之間的日期間隔數。間隔可以是幾個月,幾天,幾小時或用戶選擇的任何數量。如何查找PHP中兩個日期之間的DateIntervals數
此刻我有一個使用遞歸的函數,但是,如果由於遞歸嵌套限制而導致兩點之間存在超過100個間隔,則會中斷。
private static function findCurrentInterval($initialStartTimestamp, $intervalStrtotimeFormat, $now = null, $period = 1)
{
if (is_null($now)){
$now = time();
}
$endOfCurrentInterval = strtotime($intervalStrtotimeFormat, $initialStartTimestamp);
if ($now > $initialStartTimestamp && $now < $endOfCurrentInterval){
return new self($period);
}else{
# increment the period ID tracking variable
$period++;
return self::findCurrentInterval($endOfCurrentInterval, $intervalStrtotimeFormat, $now, $period);
}
}
我需要出來的是代表我們對哪個時間間隔的週期在當前,也就是說,如果它被設置爲7天間隔的整數值,20天已開始點之間傳遞現在,它會返回'3',因爲我們會進入第三階段。
有沒有辦法做到這一點沒有遞歸,也許使用DateInterval?
N.B.如果將其限制在幾天或幾小時內,這將非常簡單 - 但它需要支持幾個月,這可能會有不同的長度。