skip to Main Content

I am using PHP and Carbon and would like to check if two dates fall between another two dates.

As an example, say I have:

$eventStart = '2023-04-01';
$eventEnd = '2023-09-14';

$rangeStart = '2023-07-01';
$rangeEnd = '2023-07-31';

The ‘event’ which runs from 1st April until 14th September, does fall within the ‘range’ I want to check, which starts on 1st July up to 31st July.

So given any two start and end ‘event’ dates, how can I check that they fall within another two start and end ‘range’ dates?

2

Answers


  1. You can use CarbonPeriod::contains()

    Return true if the given date is between start and end.

    $eventStart = '2023-04-01';
    $eventEnd = '2023-09-14';
    
    $rangeStart = '2023-07-01';
    $rangeEnd = '2023-07-31';
    
    $eventPeriod = CarbonPeriod::create($eventStart, $eventEnd);
    $rangePeriod = CarbonPeriod::create($rangeStart, $rangeEnd);
    
    $eventPeriod->contains($rangePeriod);
    
    Login or Signup to reply.
  2. You should use CarbonPeriod::overlaps()

    Returns true if the current period overlaps the given one (if 1 parameter passed) or the period between 2 dates (if 2 parameters passed).

    $eventStart = '2023-04-01';
    $eventEnd = '2023-09-14';
    
    $rangeStart = '2023-07-01';
    $rangeEnd = '2023-07-31';
    
    $eventPeriod = CarbonPeriod::create($eventStart, $eventEnd);
    $rangePeriod = CarbonPeriod::create($rangeStart, $rangeEnd);
    
    $eventPeriod->overlaps($rangePeriod);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search