Iwani Khalid
Iwani Khalid

Reputation: 303

PHP: Find if booked dates are within any of the specified date range

I have solved my client's initial requirement when he originally asked me to assign special rate if a customer booked within a specified date range.

However, he has extended the requirement to multiple date ranges now and I'm left dumbfounded on how to manipulate the working code I had previously.

Here's the code I used previously for 1 date range

$book_start_date = $start->format('d F Y');
$book_end_date = $end->format('d F Y');

$daterange_season = array('2017-01-20', '2017-02-15'); 
/* 20 January 2017 - 15 February 2017 : Peak Season */

$daterange_booked = array($book_start_date, $book_end_date);

$range_min = new DateTime(min($daterange_season));
$range_max = new DateTime(max($daterange_season));

$start_book = new DateTime(min($daterange_booked));
$end_book = new DateTime(max($daterange_booked));

if ( $start_book >= $range_min && $end_book <= $range_max ) { 

// Apply special rate

}

Now I have multiple date ranges

2016-11-25 -----> 2017-01-02
2017-01-20 -----> 2017-02-06
2017-03-17 -----> 2017-03-27
2017-04-27 -----> 2017-05-04
2017-05-25 -----> 2017-05-31

Can anyone show me the direction to take?

FYI, I'm a CSS person actually but sometimes required to do jQuery and PHP.

Upvotes: 0

Views: 46

Answers (1)

rafwlaz
rafwlaz

Reputation: 484

This should work for You with any ranges You want.

$book_start_date = $start->format('d F Y');
$book_end_date = $end->format('d F Y');

$daterange_season = array(
     array('2017-01-20', '2017-01-25'),
     array('2017-01-29', '2017-02-15')
); 

$daterange_booked = array($book_start_date, $book_end_date);

$start_book = new DateTime(min($daterange_booked));
$end_book = new DateTime(max($daterange_booked));

foreach($daterange_season as $singleRange){

    $range_min = new DateTime(min($singleRange));
    $range_max = new DateTime(max($singleRange));

    if ( $start_book >= $range_min && $end_book <= $range_max ) { 

    // Apply special rate
        break;
    }

}

Upvotes: 3

Related Questions