C# 判断时间段是否相交

黄舟
黄舟 原创
2017-03-01 10:42:25 2358浏览

1. 判断两个起止时间是否相交:

public static bool IsTimeBetween(TimeSpan input, TimeSpan start, TimeSpan end, bool fromInclusice, bool toInclusive)
        {
            ////m.sbmmt.com/
            // see if start comes before end
            if (end < start)
            {
                return
                    ((toInclusive && (input <= end)) || (!toInclusive && (input < end)))
                    ||
                    ((fromInclusice && (input >= start)) || (!fromInclusice && (input > start)));
            }
            else
            {
                return
                    ((fromInclusice && (input >= start)) || (!fromInclusice && (input > start)))
                    &&
                    ((toInclusive && (input <= end)) || (!toInclusive && (input < end)));
            }


        }

2. 传入起止时间的表达式,判断与已知时间段的交集,生成Mongo查询:

public IMongoQuery GetMongoQueryIntersectWith<TCollection>(
            Expression<Func<TCollection, DateTime>> fromExp, 
            Expression<Func<TCollection, DateTime>> toExp)
        {
            var rangeTo = Query.And(Query<TCollection>.GTE(toExp, To), Query<TCollection>.LTE(fromExp, To));
            var rangeFrom = Query.And(Query<TCollection>.GTE(toExp, From), Query<TCollection>.LTE(fromExp, From));

            var rangeQuery = Query.Or(rangeTo, rangeFrom, 
                Query.And(Query<TCollection>.GTE(fromExp, From),Query<TCollection>.LTE(toExp, To)));
            return rangeQuery;
        }


其中From和To为两个时间属性

以上就是C# 判断时间段是否相交的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。