c# - C# 中的 DateTime 比较给出了意想不到的结果
问题描述
我有以下功能:
public bool IsAvailableForTimeslot(DateTime start, DateTime end)
{
bool startOK = true;
bool endOK = true;
foreach (var slot in ReservedSlots)
{
if (slot.Item2.AddHours(6) > start)
{
startOK = false;
}
if (slot.Item1 < end && start < slot.Item2)
{
endOK = false;
}
}
if (startOK == true && endOK == true)
return true;
else
return false;
}
// List of Tuples with already reserved timeslots, Item1 being the start en 2 the end
public List<Tuple<DateTime, DateTime>> ReservedSlots { get; set; }
当“ReservedSlots”列表中的 startdates 和时间与参数相同的年份时,该函数将正常返回所有内容,但当年份不同时,该函数将 startOK 标记为 false。
更多信息:假设我有 4 辆带有“ReservedSlots”列表的车辆。
demoVehicle0.ReservedSlots.Add(new Tuple<DateTime, DateTime>(new DateTime(2020, 1, 1, 12, 0, 0), new DateTime(2020, 1, 1, 20, 0, 0)));
demoVehicle0.ReservedSlots.Add(new Tuple<DateTime, DateTime>(new DateTime(2020, 1, 2, 3, 0, 0), new DateTime(2020, 1, 2, 13, 0, 0)));
// Works (returns false)
demoVehicle2.ReservedSlots.Add(new Tuple<DateTime, DateTime>(new DateTime(2020, 1, 1, 12, 0, 0), new DateTime(2020, 1, 1, 20, 0, 0)));
demoVehicle2.ReservedSlots.Add(new Tuple<DateTime, DateTime>(new DateTime(2020, 1, 2, 3, 0, 0), new DateTime(2020, 1, 2, 13, 0, 0)));
// Works (returns false)
demoVehicle3.ReservedSlots.Add(new Tuple<DateTime, DateTime>(new DateTime(2021, 1, 1, 1, 0, 0), new DateTime(2021, 1, 1, 5, 0, 0)));
// Doesnt work (returns false) if I change the year to 2020, it will work however
// timeslot is what is used in the parameters of the function above
var timeslot = new Tuple<DateTime, DateTime>(new DateTime(2020, 1, 1, 20, 0, 0), new DateTime(2020, 1, 2, 0, 0, 0));
解决方案
如果startOK
或endOK
变量中的任何一个在迭代结束时为 false ,则返回 false ,但仅当这两个变量对同一 slot评估为 false时才返回 false 。
你可以重组你的方法来实现这一点。
public bool IsAvailableForTimeslot(DateTime start, DateTime end)
{
foreach (var slot in ReservedSlots)
{
if (start < slot.Item2.AddHours(6) && slot.Item1 < end)
return false;
}
return true;
}
或者没有明确定义循环......
using System.Linq;
public bool IsAvailableForTimeslot(DateTime start, DateTime end)
{
return !ReservedSlots.Any(slot => start < slot.Item2.AddHours(6) && slot.Item1 < end);
}
这是有关检测重叠时段的更多信息。
推荐阅读
- amazon-web-services - 上传到 S3 失败并出现以下错误:访问被拒绝 - CodeStarConnections
- ios - 有没有办法定期唤醒 ios 应用程序?
- javascript - 在同一页面上的多个画廊上使用幻灯片功能
- selenium - 如果链接不存在,如何跳过测试用例并转到机器人框架中的下一个链接
- ruby-on-rails - 为什么 docker run 有效,但同一图像的 docker-compose 无效?
- typescript - 验证函数调用的接口
- c++ - 如何正确使用具有抽象指针类型的模板类
- .net - 在 Ubuntu 20.04 上的 Wasm 项目上构建失败
- python-3.x - Django Rest:AssertionError:无法将唯一查询与非唯一查询组合
- python - 遵循策略模式;授予对父属性/方法的接口访问权限