首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# 時間區間重疊判斷:四種情況統一邏輯與代碼實現

     編輯:程式設計綜合問答

四種重疊情況圖解


A: |----------|        B: |----------|
   1. 前半重疊               2. 後半重疊
A: |----------|        B:    |----------|
   3. 中間重疊 (B 包含 A)    4. A 包含 B
A: |------------|    B:   |------|

統一判斷邏輯:非重疊條件取反

兩區間 不重疊 僅有兩種情況:
A 結束 ≤ B 開始 或 B 結束 ≤ A 開始。
因此 重疊條件 = 非 (A.End <= B.Start || B.End <= A.Start)。

代碼實現

public bool IsOverlap(DateTime aStart, DateTime aEnd, DateTime bStart, DateTime bEnd) {
    // 校驗:開始早於結束
    if (aStart > aEnd) throw new ArgumentException("A 區間無效");
    if (bStart > bEnd) throw new ArgumentException("B 區間無效");

    // 核心判斷:取反非重疊
    return !(aEnd <= bStart || bEnd <= aStart);
    // 等價展開:
    // return aStart < bEnd && bStart < aEnd;
}

四種情況具體判斷 (如需區分類型)

類型條件代碼
前半重疊 (A 先開始,B 在 A 結束前開始) A.Start < B.Start < A.End ≤ B.End aStart < bStart && bStart < aEnd && aEnd <= bEnd
後半重疊 (B 先開始,A 在 B 結束前開始) B.Start < A.Start < B.End ≤ A.End bStart < aStart && aStart < bEnd && bEnd <= aEnd
中間重疊 (B 完全在 A 內部) A.Start ≤ B.Start < B.End ≤ A.End aStart <= bStart && bEnd <= aEnd
A 完全在 B 內部 B.Start ≤ A.Start < A.End ≤ B.End bStart <= aStart && aEnd <= bEnd

工具方法:計算重疊區間

public (DateTime start, DateTime end)? GetOverlapRange(DateTime aStart, DateTime aEnd, DateTime bStart, DateTime bEnd) {
    if (!IsOverlap(aStart, aEnd, bStart, bEnd)) return null;
    var start = aStart > bStart ? aStart : bStart; // Max
    var end = aEnd < bEnd ? aEnd : bEnd;           // Min
    return (start, end);
}

考勤/排班系統常見應用

  • 衝突檢測:新增班次時,檢查該員工當日是否有重疊班次。
  • 工時計算:多個加班區間合併去重,計算總加班時長。
  • 可用性查詢:給定會議室占用區間,查詢空閒時段 (補集)。

擴展:多區間重疊檢測 (O(N log N))

public bool HasAnyOverlap(List<(DateTime s, DateTime e)> intervals) {
    var sorted = intervals.OrderBy(x => x.s).ToList();
    for (int i = 1; i < sorted.Count; ++i) {
        if (sorted[i].s < sorted[i-1].e) return true; // 當前開始 < 前一結束 → 重疊
    }
    return false;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved