繁体   English   中英

C# 中的日期时间比较给出了意想不到的结果

[英]DateTime comparison in C# gives unexpected results

我有以下 function:

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 和时间与参数相同的年份时,function 会正常返回所有内容,但当年份不同时,function 会将 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));

如果startOKendOK变量中的任何一个在迭代结束时为 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);
}

这是有关检测重叠时段的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM