2

I can get the Hours/Minutes/Seconds difference between 2 DateTime.

But I am trying to get the common time between 2 datetime, but not.

Example:

public class Meeting
{
    public DateTime Start { get; set; }
    public DateTime End { get; set; }
}

Here I am added the times.

 var list = new List<Meeting>();
        list.Add(
            new Meeting 
            { 
                Start = DateTime.Parse("12/13/2018 09:00 AM"), 
                End = DateTime.Parse("12/13/2018 10:00 AM")
            }
        );
        list.Add(
            new Meeting 
            { 
                Start = DateTime.Parse("12/13/2018 09:45 AM"), 
                End = DateTime.Parse("12/13/2018 10:30 AM") 
            }
        );

So, here I am trying to get the commont time between 2 lists.

The common time is 15 Minutes and the Time is 9:45 AM to 10:00 AM.

So, any suggestions to get the time 9:45 AM to 10:00 AM.

RvdK
  • 19,580
  • 4
  • 64
  • 107
Manoj Kumar
  • 157
  • 3
  • 11
  • So to confirm my understanding - you want to find the `overlap` between two time periods. If this is correct, you should adjust your question accordingly to avoid confusion and help you get a speedier answer. – jazb Dec 13 '18 at 12:56
  • What you mean is: I want to get the amount of time the two Meeting object's dates are in collision with each other in? – Alen Genzić Dec 13 '18 at 12:57
  • this is the better link to mark as duplicate for: https://stackoverflow.com/questions/13513932/algorithm-to-detect-overlapping-periods – Svenmarim Dec 13 '18 at 12:58
  • @Svenmarim No, that doesn't give the date ranges. – DavidG Dec 13 '18 at 12:58
  • truee.. truee.. – Svenmarim Dec 13 '18 at 12:59

1 Answers1

3

I might be misunderstanding your question, but it seems like you want to get the overlapping time interval. I think something like this should work:

DateTime s1 = DateTime.Parse("12/13/2018 09:00 AM");
DateTime e1 = DateTime.Parse("12/13/2018 10:00 AM");
DateTime s2 = DateTime.Parse("12/13/2018 09:45 AM");
DateTime e2 = DateTime.Parse("12/13/2018 10:30 AM");

DateTime overlapStart = (s1 > s2 ? s1 : s2);
DateTime overlapEnd = (e1 < e2 ? e1 : e2);

TimeSpan overlappedTimeSpan 
    = (overlapStart < overlapEnd ? overlapEnd - overlapStart : TimeSpan.FromTicks(0));
rory.ap
  • 34,009
  • 10
  • 83
  • 174