kamalpreet kamalpreet - 3 months ago 12
C# Question

How can I check whether there is conflict in time from string like 6:00 PM to 9:00 PM

I am building something like exam datesheet. I'm currently having issues in finding conflicts between time..

I have a List of strings that stores time intervals like-

List<string> times = new List<string>();
times.Add("6:00 PM to 9:00 PM");
times.Add("10:00 AM to 1:00 PM");

Now suppose, if want to add below time to the list, I first want to check it does not conflict with the time that is already there.

So, in below case, it should not be added.

if(NotConflict("5:00 PM to 7:00 PM"))
times.Add("5:00 PM to 7:00 PM");

But the following can be added since there is no conflict.

if(NotConflict("2:00 PM to 5:00 PM"))
times.Add("2:00 PM to 5:00 PM");

I cannot use
here because it the very old system and time is being stored like above. And it being used at many places.


This should work:

private static Tuple<DateTime, DateTime> ParseDate(string dateTimes)
    var split = dateTimes.Split(new[] { " to " }, StringSplitOptions.None);
    var time1 = DateTime.ParseExact(split[0], "h:mm tt",
    var time2 = DateTime.ParseExact(split[1], "h:mm tt",

    return Tuple.Create(time1, time2);

private static bool NotConflict(IEnumerable<string> times, string time) {
    var incTime = ParseDate(time);

    return !times.Any(t => {
        var parsed = ParseDate(t);

        return incTime.Item1 <= parsed.Item2 && parsed.Item1 <= incTime.Item2;

public static void Main()
    var times = new List<string>();
    times.Add("6:00 PM to 9:00 PM");
    times.Add("10:00 AM to 1:00 PM");

    Console.WriteLine("No Conflict 5:00 PM to 7:00 PM: {0}", NotConflict(times, "5:00 PM to 7:00 PM"));
    Console.WriteLine("No Conflict 2:00 PM to 5:00 PM: {0}", NotConflict(times, "2:00 PM to 5:00 PM"));

ParseDate will return a formatted tuple with the start and end time in Item1 and Item2 respectively. Then you simply use Linq's Any function to filter and make sure that you don't return any that fall within the bounds.

See the DotNet fiddle here.