Ticker

6/recent/ticker-posts

Determine Whether Two Date Ranges Overlap in PHP

An interval is represented as a combination of start time and end time. Given a set of intervals, check if any two intervals intersect.
Examples:

$periods = [
   ['start_time' => "09:00", 'end_time' => '10:30'],
   ['start_time' => "14:30", "end_time" => "16:30"],
   ['start_time' => "11:30", "end_time" => "13:00"],
   ['start_time' => "10:00", "end_time" => "11:30"]
];
Expected time complexity is O(nLogn) where n is number of intervals.

/**
 * Check the two time periods overlap
 *
 * Example:
 * $periods = [
 *      ['start_time' => "09:00", 'end_time' => '10:30'],
 *      ['start_time' => "14:30", "end_time" => "16:30"],
 *      ['start_time' => "11:30", "end_time" => "13:00"],
 *      ['start_time' => "10:30", "end_time" => "11:30"],
 * ]
 *
 * @param $periods
 * @param string $start_time_key
 * @param string $end_time_key
 * @return bool
 */
public static function isOverlapped($periods, $start_time_key = 'start_time', $end_time_key = 'end_time')
{
    // order periods by start_time
    usort($periods, function ($a, $b) use ($start_time_key, $end_time_key) {
        return strtotime($a[$start_time_key]) <=> strtotime($b[$end_time_key]);
    });
    // check two periods overlap
    foreach ($periods as $key => $period) {
        if ($key != 0) {
            if (strtotime($period[$start_time_key]) < strtotime($periods[$key - 1][$end_time_key])) {
                return true;
            }
        }
    }
    return false;
}
In this script, i use <=> Spaceship operator, you can check it here

Post a Comment

1 Comments

  1. When it involves improving participant lifetime value and on line casino performance, our games pack a critical punch! That’s outcome of|as a outcome of} we’re passionate in regards to the product we create and we delight ourselves on making the best slots within the business. Shaul said he understands why the Missouri on line casino trade doesn't want legal growth of video playing terminals within the state. He said that the loss in income from casinos could be attributed to the competition by the unlawful machines. Acee’s is considered one of Illinois’ highest earners among video slot machine establishments, ranking No. 7 overall in internet terminal income in 2018, when it brought in $1.four million. Absher said slot machines are concentrated 원 엑스 벳 close to public housing items in Marion and instructed that municipal governments contemplate prohibiting slots within a sure distance of sponsored housing items.

    ReplyDelete