Skip to content

Instantly share code, notes, and snippets.

@svandragt
Created February 25, 2014 14:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svandragt/9209589 to your computer and use it in GitHub Desktop.
Save svandragt/9209589 to your computer and use it in GitHub Desktop.
DateRange class: Quickly find overlaps with other date ranges
<?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;
}
}
@svandragt
Copy link
Author

Example: checking for overlapping Schedules

$ThisDateRange = new DateRange($this->StartDate, $this->EndDate);

foreach ($CourseDate->Schedules() as $Schedule) {
    // Don't match the current ID
    if ($Schedule->ID == $this->ID) {
        continue;
    }
    $ScheduleDateRange = new DateRange($Schedule->StartDate, $Schedule->EndDate);
    if ($ScheduleDateRange->OverlapsWith($ThisDateRange)) {
            $result->error(sprintf("Cannot save: Another schedule (#%d) overlaps with this one.", $Schedule->ID));
            break;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment