2015-06-26 126 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

相关问题