Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Mav23Sa's avatar

count the days that overlap two date ranges

I have in the database

startDate | dateFianal |

the user enters a range of dates and I have to find if there are days that fall within the period in the database

example:

startDateDB | dateFinalDB | 2021-10-10 | 2021-10-20

startDateUser | dateFinalUser | 2021-10-09 | 2021-10-18

in this case I need to return 8 days

how can I do this??

0 likes
5 replies
jlrdw's avatar

Carbon has a diffInDays. You may need to get answer and substract 1 (one), since you need between.

1 like
tykus's avatar

If there is no method already defined on CarbonPeriod; then you can add one:

use Carbon\CarbonPeriod;
// ...
CarbonPeriod::macro('overlap', function ($other) {
    if (!$this->overlaps($other)) return 0;

   return min($this->end, $other->end)
     ->diff(max($other->start,$this->start))
     ->days;
});

You can define this in Service Provider; then use it as follows:

$p1 = new CarbonPeriod('2021-10-10', 'P1D', '2021-10-20');
$p2 = new CarbonPeriod( '2021-10-09', 'P1D', '2021-10-18');
echo $p1->overlap($p2);
2 likes
Mav23Sa's avatar

@tykus ok, this work and return true or false if the period overlap. but I also need to know the number of days that the two dates overlap.

I have this code that works, but I remember that carbon had a function that could verify the days that two periods overlapped

$period = CarbonPeriod::between($startDateBD, $finalDateBD);

    $from= Carbon::parse($startDateUser);
    $to = Carbon::parse($finalDateUser);

    $days = 0;

    if ($period->overlaps($from, $to)) {
        foreach ($period as $day) {
            if ($day->between($from, $to)) {
                $days++;
            }
        }
    }
tykus's avatar

@Mav23Sa whatever I gave you above works. Like most programming problems, there are potentially many solutions.

1 like

Please or to participate in this conversation.