Critical Developers

Programmers Knowledge Base

Validate If Dates Overlap in Multiple Date Ranges - ASP.Net

Let' s assume we have 3 date ranges.

Algorithm To Check If Dates Overlap in Date Ranges:-

1 - Declare a Empty List<> of DateTime Type.

2 - Extract All Dates from all given Date Range as a DateTime List<>.

3 - Add all extracted dates list to the empty List<> as in point-1 one-by-one.

4 - Get the count of List.

5 - Get the Distinct count of List.

6 -  If count of point-5 < count of point-4 then its overlapped else no overlapped found.

Please find the code in as below:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class TestOverlapDates : System.Web.UI.Page

    protected void Page_Load(object sender, EventArgs e)


    protected void btnTestOverlap_Click(object sender, EventArgs e)
        if (IsDatesOverlaps() == true)
            Label1.Text = "Status:- Overlapped Date Ranges";
            Label1.Text = "Status:- Non Overlapped Date Ranges";

    private bool IsDatesOverlaps()
        bool lbIsOverlap = false;
        DateTime ldtFromDate1 = Convert.ToDateTime(TextBox1.Text);
        DateTime ldtToDate1 = Convert.ToDateTime(TextBox2.Text);
        DateTime ldtFromDate2 = Convert.ToDateTime(TextBox3.Text);
        DateTime ldtToDate2 = Convert.ToDateTime(TextBox4.Text);
        DateTime ldtFromDate3 = Convert.ToDateTime(TextBox5.Text);
        DateTime ldtToDate3 = Convert.ToDateTime(TextBox6.Text);

        List<DateTime> loAllDatesInRanges = new List<DateTime>();
        loAllDatesInRanges.AddRange(GetDateRangeDaily(ldtFromDate1, ldtToDate1));
        loAllDatesInRanges.AddRange(GetDateRangeDaily(ldtFromDate2, ldtToDate2));
        loAllDatesInRanges.AddRange(GetDateRangeDaily(ldtFromDate3, ldtToDate3));
        int liTotalDaysCount = loAllDatesInRanges.Count();                 // To Select All Dates Count
        int liDistinctDaysCount = loAllDatesInRanges.GroupBy(item => item).Count();   // To Select Distinct Dates Count
        if (liDistinctDaysCount < liTotalDaysCount)
            lbIsOverlap = true;         // Oops! Overlapped

        return lbIsOverlap;

    private static List<DateTime> GetDateRangeDaily(DateTime fdtStartDate, DateTime fdtEndDate)
        if (fdtStartDate > fdtEndDate)
            return null;
        List<DateTime> loDates = new List<DateTime>();
        DateTime tmpDate = Convert.ToDateTime(fdtStartDate.ToShortDateString());
            tmpDate = tmpDate.AddDays(1);
        } while (tmpDate <= fdtEndDate);
        return loDates;