Friday, February 1, 2013

How to know if a Date is in range between two Dates in C#

Let's say that we have a DateTime = Jan 1, 2012 and we want to check if this date is between 2 other dates.
The following code example Implements IRange interface that can be used with Integers too.
public interface IRange
    {
        T Start { get; }
        T End { get; }
        bool WithInRange(T value);
        bool WithInRange(IRange range);
    }

    public class DateRange : IRange
    {
        public DateTime Start { get; set; }
        public DateTime End { get; set; }

        public DateRange(DateTime start, DateTime end)
        {
            Start = start;
            End = end;
        }

        public bool WithInRange(DateTime value)
        {
            return (Start <= value) && (value <= End);
        }

        public bool WithInRange(IRange range)
        {
            return (Start <= range.Start) && (range.End <= End);
        }
    }

This is how to use this class function:
DateTime startDate = new DateTime(2011, 1, 1);
        DateTime endDate = new DateTime(2013, 1, 1);
        DateTime inRange = new DateTime(2012, 1, 1);
        DateTime outRange = new DateTime(2010, 1, 1);
        DateRange range = new DateRange(startDate, endDate);
        bool yes = range.WithInRange(inRange);
        bool no = range.WithInRange(outRange);

Source: https://www.nilebits.com/blog/2013/01/how-to-know-if-a-date-is-in-range-between-two-dates-in-c-net/

No comments:

Post a Comment