Created
February 25, 2014 14:16
-
-
Save svandragt/9209589 to your computer and use it in GitHub Desktop.
DateRange class: Quickly find overlaps with other date ranges
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Class to make it easier to compare date ranges (where range is between start date and end date) | |
*/ | |
class DateRange { | |
public $StartDate = null; | |
public $EndDate = null; | |
/** | |
* Accept string dates, Date & DateTime objects | |
* @param [mixed] $StartDate | |
* @param [mixed] $EndDate | |
*/ | |
public function __construct($StartDate = null, $EndDate = null) { | |
$valid_classes = array('Date','SS_DateTime'); | |
foreach (array('StartDate','EndDate') as $property) { | |
if (empty($$property)) { | |
return; | |
} | |
if (!is_object($$property) ) { | |
$obj = DBField::create_field('Date',null); | |
$obj->setValue($$property); | |
} else { | |
foreach ($valid_classes as $class) { | |
if (get_class($$property) == $class) { | |
$obj = $$property; | |
break; | |
} | |
} | |
user_error('Class is not: ' . implode(', ', $valid_classes)); | |
} | |
$this->$property = $obj; | |
} | |
} | |
/** | |
* Does the current daterange overlap with the provided daterange? | |
* @param [DateRange] $DateRange Provided daterange | |
*/ | |
public function OverlapsWith(DateRange $DateRange) { | |
if ( $this->StartDate <= $DateRange->EndDate && $DateRange->StartDate <= $this->EndDate ) { | |
return true; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: checking for overlapping Schedules