How do I find how many days are within a date range that are within another date range in PHP?

188 views Asked by At

I'm using Carbon PHP library.The answer in the duplicate question uses PHP's built in function.

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


Below is the code that I use to find if a date range($userDateStart and $userDateEnd) is with in another date range ($couponStart and$couponEnd`) and it works fine without any error but I don't know how to find the days that overlap/exists that is in this date range?

The library I'm using is http://carbon.nesbot.com/docs/

The expected result should be 4 in this case..Hope you will help me.

$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");
1

There are 1 answers

1
Twister1002 On BEST ANSWER

According to the Documentation that was provided, You need to use this:

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

So to work with your program I'm thinking you'll need to do this:

$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

Please note: This was not tested as I do not have Carbon's library installed.