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>
    {
        T Start { get; }
        T End { get; }
        bool WithInRange(T value);
        bool WithInRange(IRange<T> range);
    }

    public class DateRange : IRange<DateTime>
    {
        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<DateTime> 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);

Hire Me

Follow me on Facebook

Follow me

Do you find this Blog helpful?

Follow by Email

About Me

My Photo
Expert Senior Software Developer

Microsoft Business Card