Returns true if the event overlaps at all with the time period within
the start and end time.

@param \DateTime $start
@param \DateTime $end
@return bool
767138
public function overlaps(\DateTime $start, \DateTime $end) {
    $overlaps = FALSE;

    if ($this->dateIsEarlier($start) &&
      ($this->dateIsInRange($end) || $this->dateIsLater($end))) {
      $overlaps = TRUE;
    } elseif ($this->dateIsInRange($start) &&
      ($this->dateIsInRange($end) || $this->dateIsLater($end))) {
      $overlaps = TRUE;
    }

    return $overlaps;
  }
1055634
public static function diffDateTimeDays($dateTimeStart, $dateTimeEnd)
    {
        $dateStart = self::cutTime($dateTimeStart);
        $dateEnd = self::cutTime($dateTimeEnd);
        $secondsDiff = self::diffDateTimeSeconds($dateStart, $dateEnd);
        $daysDiff = $secondsDiff / 3600 / 24;
        return $daysDiff;
    }
962046
public function endsLater(\DateTime $date) {
    $later = FALSE;

    $t2 = $this->end_date->getTimeStamp();

    $t4 = $date->getTimestamp();

    if ($t2 > $t4) {
      $later = TRUE;
    }

    return $later;
  }
402348
protected function update_loop_times($start, $end) {
        $avg = intval(($start + $end) / 2);
        return array($start, $avg, $end);
    }
455206
public function add($start, $end, $type)
    {
        if ($start > $this->end || $end < $this->start) {
            // This new data is outside our timerange.
            return;
        }

        if ($start < $this->start) {
            // The item starts before our requested time range
            $start = $this->start;
        }
        if ($end > $this->end) {
            // The item ends after our requested time range
            $end = $this->end;
        }

        // Finding out where we need to insert the new item.
        $currentIndex = 0;
        while ($start > $this->data[$currentIndex]['end']) {
            ++$currentIndex;
        }

        // The standard insertion point will be one _after_ the first
        // overlapping item.
        $insertStartIndex = $currentIndex + 1;

        $newItem = [
            'start' => $start,
            'end' => $end,
            'type' => $type,
        ];

        $preceedingItem = $this->data[$insertStartIndex - 1];
        if ($this->data[$insertStartIndex - 1]['start'] === $start) {
            // The old item starts at the exact same point as the new item.
            --$insertStartIndex;
        }

        // Now we know where to insert the item, we need to know where it
        // starts overlapping with items on the tail end. We need to start
        // looking one item before the insertStartIndex, because it's possible
        // that the new item 'sits inside' the previous old item.
        if ($insertStartIndex > 0) {
            $currentIndex = $insertStartIndex - 1;
        } else {
            $currentIndex = 0;
        }

        while ($end > $this->data[$currentIndex]['end']) {
            ++$currentIndex;
        }

        // What we are about to insert into the array
        $newItems = [
            $newItem,
        ];

        // This is the amount of items that are completely overwritten by the
        // new item.
        $itemsToDelete = $currentIndex - $insertStartIndex;
        if ($this->data[$currentIndex]['end'] <= $end) {
            ++$itemsToDelete;
        }

        // If itemsToDelete was -1, it means that the newly inserted item is
        // actually sitting inside an existing one. This means we need to split
        // the item at the current position in two and insert the new item in
        // between.
        if (-1 === $itemsToDelete) {
            $itemsToDelete = 0;
            if ($newItem['end'] < $preceedingItem['end']) {
                $newItems[] = [
                    'start' => $newItem['end'] + 1,
                    'end' => $preceedingItem['end'],
                    'type' => $preceedingItem['type'],
                ];
            }
        }

        array_splice(
            $this->data,
            $insertStartIndex,
            $itemsToDelete,
            $newItems
        );

        $doMerge = false;
        $mergeOffset = $insertStartIndex;
        $mergeItem = $newItem;
        $mergeDelete = 1;

        if (isset($this->data[$insertStartIndex - 1])) {
            // Updating the start time of the previous item.
            $this->data[$insertStartIndex - 1]['end'] = $start;

            // If the previous and the current are of the same type, we can
            // merge them into one item.
            if ($this->data[$insertStartIndex - 1]['type'] === $this->data[$insertStartIndex]['type']) {
                $doMerge = true;
                --$mergeOffset;
                ++$mergeDelete;
                $mergeItem['start'] = $this->data[$insertStartIndex - 1]['start'];
            }
        }
        if (isset($this->data[$insertStartIndex + 1])) {
            // Updating the start time of the next item.
            $this->data[$insertStartIndex + 1]['start'] = $end;

            // If the next and the current are of the same type, we can
            // merge them into one item.
            if ($this->data[$insertStartIndex + 1]['type'] === $this->data[$insertStartIndex]['type']) {
                $doMerge = true;
                ++$mergeDelete;
                $mergeItem['end'] = $this->data[$insertStartIndex + 1]['end'];
            }
        }
        if ($doMerge) {
            array_splice(
                $this->data,
                $mergeOffset,
                $mergeDelete,
                [$mergeItem]
            );
        }
    }
114866
public function intersect(Period $period)
	    {
	        if (! $this->overlaps($period)) {
	            throw new LogicException('Both Period objects should overlaps');
	        }

	        $start = $this->start;

	        if ($period->start > $start) {
	            $start = $period->start;
	        }

	        $end = $this->end;
	        
	        if ($period->end < $end) {
	            $end = $period->end;
	        }

	        return new self($start, $end);
	    }
1187491
public function isWithinOneDay()
	{
		$started = (is_null($this->started)) ? new \DateTime('now') : $this->started;
		$stopped = (is_null($this->stopped)) ? new \DateTime('now') : $this->stopped;

		return ($started->format('Y-m-d') === $stopped->format('Y-m-d'));
	}
1003758
public function setEnd($end, $write=true)
    {
        $e = $this;

        if ($e->TimeFrameType == 'DateTime') {
            $e->EndDateTime = $end;
        } elseif ($e->TimeFrameType == 'Duration') {
            $duration = $this->calcDurationBasedOnEndDateTime($end);
            if ($duration) {
                $e->Duration = $duration;
            } else {
                //if duration is more than 1 day, make the time frame "DateTime"
                $e->TimeFrameType = 'DateTime';
                $e->EndDateTime = $end;
            }
        }

        if ($write) {
            $e->write();
        }
    }
41503
public function spans($time_period)
    {
        $time_period = self::parseTimePeriod($time_period);

        // If the date range does not have a bound then it will not span any time periods.
        if (! $this->isBounded()) {
            return false;
        }

        // After must be positioned at the end of the time period
        $end = self::forTimePeriod($time_period, $this->after)->end();
        if (! $end->eq($this->after)) {
            return;
        }

        // Before must be positioned at the start of the time period
        $start = self::forTimePeriod($time_period, $this->before)->start();
        if (! $start->eq($this->before)) {
            return;
        }

        // The start of the date range should equal the end of the date range set back to the start of its time period.
        // This ensures that the range spans only a single time period; otherwise if we only checked the bounds, they
        // could be two or more time periods apart.
        if (! self::forTimePeriod($time_period, $this->end())->start()->eq($this->start())) {
            return;
        }

        return $this->start();
    }
1003417
protected function _dateDiff($start = null, $stop = null) {
		if ($start) {
			$endDate = $stop instanceof DateTime ? $stop : new DateTime($stop ? $stop : 'now');
			$startDate = $start instanceof DateTime ? $start : new DateTime($start);
			$diff = $startDate->diff($endDate)->format(Configure::read('Task.dateDiffFormat'));
			return $this->_isCli ? $diff : $this->Html->tag('span', $diff);
		} else {
			return $this->_none();
		}
	}
802286
public function calcDurationBasedOnEndDateTime($end)
    {
        $startDate = strtotime($this->StartDateTime);
        $endDate = strtotime($end);

        $duration = $endDate - $startDate;
        $secsInDay = 60 * 60 * 24;
        if ($duration > $secsInDay) {
            //Duration cannot be more than 24h
            return false;
        }

        //info on this calculation here:
        //http://stackoverflow.com/questions/3856293/how-to-convert-seconds-to-time-format
        $formatDate = gmdate("H:i", $duration);

        return $formatDate;
    }
178442
public function overlap(DatePeriodDateTime $comparison) : bool
    {
        $start = $this;
        $end = $this->getEndDate();

        $comparisonStart = $comparison;
        $comparisonEnd = $comparison->getEndDate();

        /*
         *            L     H
         * C :        |_____|
         * 1 :      __|__   |
         * 2 :     ___|     |
         * 3 :        |   __|___
         * 4 :        |     |___
         * 5 :      __|_____|__
         * 6 :        |_____|___
         * 7 :      __|_____|
         * 8 :        |_____|
         * 9 :   __   |     |
         * 10:        |     | __
         * 11:        |  __ |
         */

        // case 1
        if ($start->lt($comparisonStart) && $comparisonStart->gt($start) && $end->lt($comparisonEnd) && $end->gt($comparisonStart)) {
            return true;
        }

        // case 2
        if ($end->eq($comparisonStart)) {
            return false;
        }

        // case 3
        if ($start->gt($comparisonStart) && $start->lt($comparisonEnd) && $end->gt($comparisonEnd)) {
            return true;
        }

        // case 4
        if ($start->eq($comparisonEnd)) {
            return false;
        }

        // case 5
        if ($start->lt($comparisonStart) && $end->gt($comparisonEnd)) {
            return true;
        }

        // case 6
        if ($start->eq($comparisonStart) && $end->gt($comparisonEnd)) {
            return true;
        }

        // case 7
        if ($start->lt($comparisonStart) && $end->eq($comparisonEnd)) {
            return true;
        }

        // case 8
        if ($start->eq($comparisonStart) && $end->eq($comparisonEnd)) {
            return true;
        }

        // case 11
        if ($start->gt($comparisonStart) && $end->lt($comparisonEnd)) {
            return true;
        }

        return false;
    }
365598
public function getOneTimeEvents($starttime = null, $endtime = null) {

		if (is_null($starttime)) {
			$starttime = time();
		}
		if (is_null($endtime)) {
			$endtime = strtotime('+1 year', $starttime);
		}

		$starttime = sanitize_int($starttime);
		$endtime = sanitize_int($endtime);
		$relationship_name = sanitize_string(self::EVENT_CALENDAR_RELATIONSHIP);

		$dbprefix = elgg_get_config('dbprefix');

		// for performance we'll denormalize metastrings first
		$mdr_name = elgg_get_metastring_id('repeat');
		$mdr_val = elgg_get_metastring_id(0);
		$mds_name = elgg_get_metastring_id('start_timestamp');
		$mde_name = elgg_get_metastring_id('end_timestamp');
		$options = array(
			'type' => 'object',
			'subtype' => Event::SUBTYPE,
			'joins' => array(
				"JOIN {$dbprefix}entity_relationships er ON er.guid_one = e.guid", // calendar relationship
				"JOIN {$dbprefix}metadata mdr ON mdr.entity_guid = e.guid", // repeating metadata
				"JOIN {$dbprefix}metadata mds ON mds.entity_guid = e.guid", // start time metadata
				"JOIN {$dbprefix}metastrings mss ON mss.id = mds.value_id", // start time metastring
				"JOIN {$dbprefix}metadata mde ON mde.entity_guid = e.guid", // end time metadata
				"JOIN {$dbprefix}metastrings mse ON mse.id = mde.value_id" // end time metastring
			),
			'wheres' => array(
				"er.guid_two = {$this->guid} AND er.relationship = '{$relationship_name}'",
				"mdr.name_id = {$mdr_name} AND mdr.value_id = {$mdr_val}",
				"mds.name_id = {$mds_name}",
				"mde.name_id = {$mde_name}",
				"((CAST(mss.string AS SIGNED) BETWEEN {$starttime} AND {$endtime})
					OR (CAST(mse.string AS SIGNED) BETWEEN {$starttime} AND {$endtime}))"
			),
			'limit' => false
		);

		return new ElggBatch('elgg_get_entities', $options);
	}
16290
public Collection<Event> getEvents(final DateTime start, final DateTime end) {
        final Interval interval = new Interval(start, end);
        final Predicate<Event> withinInterval = new Predicate<Event>() {
            public boolean apply(Event input) {
                return interval.contains(input.getStart());
            }
        };
        final Collection<Event> values = eventById.values();
        return Collections2.filter(values, withinInterval);
    }
1267950
public function getAllEvents($starttime = null, $endtime = null) {

		if (is_null($starttime)) {
			$starttime = time();
		}
		if (is_null($endtime)) {
			$endtime = strtotime('+1 year', $starttime);
		}

		$starttime = sanitize_int($starttime);
		$endtime = sanitize_int($endtime);
		$relationship_name = sanitize_string(self::EVENT_CALENDAR_RELATIONSHIP);

		$dbprefix = elgg_get_config('dbprefix');

		$mds_name = elgg_get_metastring_id('start_timestamp');
		$mdre_name = elgg_get_metastring_id('repeat_end_timestamp');

		$options = array(
			'type' => 'object',
			'subtype' => Event::SUBTYPE,
			'joins' => array(
				"JOIN {$dbprefix}entity_relationships er ON er.guid_one = e.guid", // calendar relationship
				"JOIN {$dbprefix}metadata mds ON mds.entity_guid = e.guid", // start time metadata
				"JOIN {$dbprefix}metastrings mss ON mss.id = mds.value_id", // start time metastring
				"JOIN {$dbprefix}metadata mdre ON mdre.entity_guid = e.guid", // repeat end time metadata
				"JOIN {$dbprefix}metastrings msre ON msre.id = mdre.value_id" // repeat end time metastring
			),
			'wheres' => array(
				"er.guid_two = {$this->guid} AND er.relationship = '{$relationship_name}'",
				"mds.name_id = {$mds_name}",
				"mdre.name_id = {$mdre_name}",
				// event start is before our endtime AND (repeat end is after starttime, or there is no repeat end)
				"((CAST(mss.string AS SIGNED) < {$endtime}) AND (CAST(msre.string AS SIGNED) > {$starttime} OR CAST(msre.string AS SIGNED) = 0))"
			),
			'limit' => false
		);

		return new ElggBatch('elgg_get_entities', $options);
	}
414692
public function isDueNow(\DateTime $moment)
    {
        $startInterval = new \DateTime();
        $startInterval->modify('-'.$this->schedulerInterval.' mins');
        if($moment > $startInterval && $moment <= new \DateTime()){
            return true;
        } else {
            return false;
        }
    }
405352
public function setDates($start, $end)
    {
        $this->setStartDate($start);
        $this->setEndDate($end);

        return $this;
    }