2015-06-26 74 views
-1

我使用碳PHP庫。重複問題中的答案使用PHP的內置函數。如何查找PHP中另一個日期範圍內的日期範圍內有多少天?

count how many days within a date range are within another date range


下面是我用它來找到,如果日期範圍($userDateStart$userDateEnd)是與另一個日期範圍($couponStart and $ couponEnd`)的代碼,它沒有任何錯誤工作正常,但我不知道如何找到這個日期範圍內重疊/存在的日子?

我使用的庫是http://carbon.nesbot.com/docs/

預期的結果應該是4在這case..Hope你會幫我的。

$userDateStart = Carbon::createFromFormat('Y-m-d','2015-06-26'); 
$userDateEnd = Carbon::createFromFormat('Y-m-d','2015-06-29'); 

$couponStart = Carbon::createFromFormat('Y-m-d','2015-06-26'); 
$couponEnd = Carbon::createFromFormat('Y-m-d','2015-10-31'); 

if(($userDateStart >= $couponStart && $userDateEnd <= $couponEnd) || 
    ($couponStart >= $userDateStart && $couponEnd <= $userDateEnd)){ 
    die("Yes,The date is within this date range"); 
} 
die("No,It is not within this date range"); 
+4

您在理解上一個問題的答案時遇到的困難與問題是否重複無關。 –

+0

我使用碳PHP庫。確實有一些其他簡單的方法來計算日子。 – user3407278

+4

可能重複[count在一個日期範圍內有多少天是在另一個日期範圍內](http://stackoverflow.com/questions/13227912/count-how-many-days-within-a-date-range-are-在另一個日期範圍內) – rogerdeuce

回答

0

根據系統提供的文檔,你需要使用:

$dt = Carbon::create(2012, 4, 30, 0); 
echo $dt->diffInDays($dt->copy()->addMonth()); // 30 
echo $dt->diffInDays($dt->copy()->addWeek()); // 7 

因此,爲了與你的程序的工作我想你需要這樣做:

$userDateStart = Carbon::createFromFormat('Y-m-d','2015-06-26'); 
$userDateEnd = Carbon::createFromFormat('Y-m-d','2015-06-29'); 

$couponStart = Carbon::createFromFormat('Y-m-d','2015-06-26'); 
$couponEnd = Carbon::createFromFormat('Y-m-d','2015-10-31'); 

//Determin the highest date from the starts and the minimum dates from the ends 
$startBetweenDate = $userDateStart->max($couponStart); 
$endBetweenDate = $userDateEnd->min($couponEnd); 

//Now find how many days are between 
echo $startBetweenDate->diffInDays($endBetweenDate); //Should be 4 

請注意:由於我沒有安裝Carbon的庫,因此未進行測試。

+0

感謝這個解決方案,但它不適用於一些罕見的情況。 – user3407278

相關問題