Home  >  Article  >  Backend Development  >  C# Determine whether time periods intersect

C# Determine whether time periods intersect

黄舟
黄舟Original
2017-03-01 10:42:252891browse

1. Determine whether two start and end times intersect:

public static bool IsTimeBetween(TimeSpan input, TimeSpan start, TimeSpan end, bool fromInclusice, bool toInclusive)
        {
            //http://www.php.cn/
            // 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. Pass in the expression of the start and end times, determine the intersection with the known time period, and generate a Mongo query:

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 and To are two time attributes

The above is the content of C# to determine whether the time period intersects. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn