gpt4 book ai didi

c# - 如何检查 6 :00 PM to 9:00 PM 等字符串是否存在时间冲突

转载 作者:太空宇宙 更新时间:2023-11-03 23:09:58 28 4
gpt4 key购买 nike

我正在构建类似考试日期表的内容。我目前在查找时间之间的冲突时遇到问题..

我有一个存储时间间隔的字符串列表,例如-

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 函数进行过滤并确保您不会返回任何落在边界内的内容。

参见 DotNet fiddle here .

关于c# - 如何检查 6 :00 PM to 9:00 PM 等字符串是否存在时间冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39643167/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com