How to know if a date is in range between two dates in C#.NET
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);
Comments (2)
Very succinct code and just what I was looking for. Thank you!
I think you need to allow for whether or not to include the end date, particularly because your dates are defined as DateTime. If my range is 1/1/2023 – 1/31/2023 and I pass a date of 1/31/2023 01:01:01, it will return false.
I think using a generic type like this becomes difficult with date ranges. Dates and Integers don’t behave the same way.
Dates are tricky 😉