簡體   English   中英

如何確定多個(n)日期時間范圍何時相互重疊

[英]How to determine when multiple(n) datetime ranges overlap each other

我正在尋找一個可以調用的函數,該函數可以告訴我所有(p)個人同時可用的日期時間范圍。 請為我提供Objective-c或Swift語言。

p1: start: "2016-01-01 12:00", end: "2016-05-01 03:00"
p2: start: "2016-01-01 03:00", end: "2016-05-01 03:00"
p3: start: "2016-01-01 03:00", end: "2016-04-30 13:31"

在以上示例中,答案應為:

start: 2016-04-30 12:00, end: 2016-04-30 13:31

將日期對轉換為NSDateInterval對象,並采用它們的交集:

https://developer.apple.com/documentation/foundation/nsdateinterval/1641645-intersectionwithdateinterval

該文檔甚至提供了一個相當不錯的圖表:

在此處輸入圖片說明

您需要執行以下步驟:

  1. 將您的日期字符串轉換為Date對象。
  2. 使用開始和結束日期對象創建DateIntervals。
  3. 遍歷區間並檢查交叉點。

這是我可以快速提出的快速代碼:

func answer()  {
    let dateFormat = "yyyy-MM-dd HH:mm Z"
    // Date ranges
    let times = [["start": "2016-01-01 12:00 +0000", "end": "2016-05-01 03:00 +0000"],
                 ["start": "2016-01-01 03:00 +0000", "end": "2016-05-01 03:00 +0000"],
                 ["start": "2016-01-01 03:00 +0000", "end": "2016-04-30 13:31 +0000"]]

    var intervals = [DateInterval]()
    // Loop through date ranges to convert them to date intervals
    for item in times {
        if let start = convertStringToDate(string: item["start"]!, withFormat: dateFormat),
            let end = convertStringToDate(string: item["end"]!, withFormat: dateFormat) {
            intervals.append(DateInterval(start: start, end: end))
        }
    }

    // Check for intersection
    let intersection = intersect(intervals: intervals)
    print(intersection)
}

// Converts the string to date with given format
func convertStringToDate(string: String, withFormat format: String)  -> Date? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = format
    return dateFormatter.date(from: string)
}

// Cehck for intersection among the intervals in the given array and return
    // the interval if found.
    func intersect(intervals: [DateInterval]) -> DateInterval? {
        // Algorithm:
        // We will compare first two intervals.
        // If an intersection is found, we will save the resultant interval
        // and compare it with the next interval in the array.
        // If no intersection is found at any iteration
        // it means the intervals in the array are disjoint. Break the loop and return nil
        // Otherwise return the last intersection.

        var previous = intervals.first
        for (index, element) in intervals.enumerated() {
            if index == 0 {
                continue
            }

            previous = previous?.intersection(with: element)

            if previous == nil {
                break
            }
        }

        return previous
    }

注意:請通過幾個示例進行測試。 我測試了上述日期范圍及其工作正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM