# Matching dates within a monthly Interval that crosses over multiple years with PHP and Carbon

> Today I Learned by Graffino: short tips and tricks our team discovers in everyday work on code, web development, DevOps and sysops.

- URL: https://graffino.com/til/matching-dates-within-a-monthly-interval-that-crosses-over-multiple-years-with-php-and-carbon
- Author: Nick Ciolpan
- Channel: php
- Published: 2022-12-08
- Updated: 2024-01-31

```
function getDatesInRange($dates, $start, $end) {
    $datesInRange = $dates->filter(function ($date) use ($start, $end) {
        if ((int) $start->format('Y') === (int) $end->format('Y')) {
            $start->year((int)$date->format('Y'));
            $end-> year((int)$date->format('Y'));
        } elseif ((int) $start->format('Y') < (int) $end->format('Y')) {
            if ((int) $date->format('m') >= (int) $start->format('m')) {
                $start->year((int) $date->format('Y'));
                $end->year((int) $date->format('Y'))->addYears(1);
            } else {
                $end->year((int) $date->format('Y'));
                $start->year((int) $date->format('Y'))->subYears(1);
            }
        }

        return Carbon::parse($date)->isBetween($start, $end);
    });

    return $datesInRange;
}
```
