簡體   English   中英

如何檢查字符串是否存在時間沖突,如下午6:00到晚上9:00

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

我正在構建類似於考試日程表的內容。 我目前在尋找時間之間的沖突方面存在問題。

我有一個字符串列表,存儲時間間隔像 -

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

現在假設,如果想要將下面的時間添加到列表中,我首先要檢查它是否與已經存在的時間沖突。

所以,在下面的情況下,不應該添加它。

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

但是由於沒有沖突,可以添加以下內容。

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

我不能在這里使用DateTime ,因為它非常舊的系統和時間存儲如上。 它被用在很多地方。

這應該工作:

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",
                                        CultureInfo.InvariantCulture);
    var time2 = DateTime.ParseExact(split[1], "h:mm tt",
                                        CultureInfo.InvariantCulture);

    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將分別在Item1Item2返回帶有開始和結束時間的格式化元組。 然后你只需使用Linq的Any函數進行過濾,並確保不返回任何屬於范圍內的Any函數。

這里查看DotNet小提琴。

暫無
暫無

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

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