C# 检查两个时间跨度之间的时间跨度

标签 c# timespan

首先我检查了这个解决方案:

Find if current time falls in a time range

并尝试比较该解决方案的时间跨度

public Boolean CalculateDalUren(DateTime datum, TimeSpan? dalStart, TimeSpan? dalEnd)
    {
        Boolean isDal = false;
        TimeSpan timeBetween = datum.TimeOfDay;

        if ((timeBetween >= dalStart))&&(timeBetween < dalEnd)
            {
                isDal = true;
            }
        }
        return isDal;
    }

请注意,dalStart 是 21:00 或 23:00,dalEnd 几乎总是 07:00。我将 DateTime 转换为 Timespan

现在,如果时间跨度例如是 23:00,那么时间会比 dalStart 更大或相同,但因为(这是一个假设)它晚于 dalEnd > 它仍然会将 if 语句视为 false。 02:00 时反之亦然。那么它不会晚于 dalStart,而是早于 dalEnd

我认为这是因为我的时间跨度为 2 天。当日 21:00 至次日 07:00。有解决方法吗?这样我就可以检查时间是否在 21:00 到第二天早上 07:00 之间。

最佳答案

我认为这符合您的要求。

如果dalEnd小于dalStart,则应该是第二天的TimeSpan。

    public Boolean CalculateDalUren(DateTime datum, TimeSpan? dalStart, TimeSpan? dalEnd)
    {
        Boolean isDal = false;
        DateTime StartDate = DateTime.Today; 
        DateTime EndDate = DateTime.Today;

        //Check whether the dalEnd is lesser than dalStart
        if (dalStart >= dalEnd)
        {
            //Increase the date if dalEnd is timespan of the Nextday 
            EndDate = EndDate.AddDays(1); 
        }

        //Assign the dalStart and dalEnd to the Dates
        StartDate = StartDate.Date + dalStart.Value; 
        EndDate = EndDate.Date + dalEnd.Value;

        if ((datum >= StartDate) && (datum <= EndDate))
        {
            isDal = true;
        }
        return isDal;
    }

尝试一下。

关于C# 检查两个时间跨度之间的时间跨度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38741050/

相关文章:

c# - 我怎样才能使我的函数在 ArrayList 上以 "Contains"的速度运行?

c# - 如何比较列表并有效地获得最频繁的对?

c# - 使用 iTextSharp 从 pdf 中提取图像及其名称

c# - 是否可以针对多个身份验证提供程序来保护 ASP.NET Web API 2 应用程序的安全?

C# - 如何将 SQL Server 时间(7)检索到 TimeSpan

c# - 使用 DataRowExtension 解析 TimeSpan

sql - 查询最大并发时间跨度数

c# - IndexOf() 与 Replace() 和零宽度非连接器

c# - TimeSpan.ParseExact(毫秒)

c# - 在整场比赛中获得两队最大领先优势