How to find out if a DateTime is between DateRange in C #

I need to know if a date exists between DateRange. I have three dates:

// The date range DateTime startDate; DateTime endDate; DateTime dateToCheck; 

A simple solution makes a comparison, but is there a smarter way to do this?

Thanks in advance.

+50
c # datetime date-range
Jan 24 2018-11-11T00:
source share
5 answers

No, a simple comparison looks good to me:

 return dateToCheck >= startDate && dateToCheck < endDate; 

What to think about:

  • DateTime is a somewhat odd type in time zones. It can be UTC, it can be "local", it can be ambiguous. Make sure you compare apples to apples.
  • Consider whether your starting and ending points should include or exclude. I made the code above, treating it as an inclusive lower bound and an exceptional upper bound.
+83
Jan 24 '11 at 11:50
source share

Usually I create a Fowler Range for such things.

 public interface IRange<T> { T Start { get; } T End { get; } bool Includes(T value); bool Includes(IRange<T> range); } public class DateRange : IRange<DateTime> { public DateRange(DateTime start, DateTime end) { Start = start; End = end; } public DateTime Start { get; private set; } public DateTime End { get; private set; } public bool Includes(DateTime value) { return (Start <= value) && (value <= End); } public bool Includes(IRange<DateTime> range) { return (Start <= range.Start) && (range.End <= End); } } 

Usage is quite simple:

 DateRange range = new DateRange(startDate, endDate); range.Includes(date) 
+50
Jan 24 '11 at 12:02
source share

You can use extension methods to make it more readable:

 public static class DateTimeExtensions { public static bool InRange(this DateTime dateToCheck, DateTime startDate, DateTime endDate) { return dateToCheck >= startDate && dateToCheck < endDate; } } 

Now you can write:

 dateToCheck.InRange(startDate, endDate) 
+28
Jan 24 2018-11-11T00:
source share

You can use:

 return (dateTocheck >= startDate && dateToCheck <= endDate); 
+7
Jan 24 '11 at 11:50
source share

Ive found the following library most useful when doing any kind of date math. I am still surprised that this is part of the .Net infrastructure.

http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET

+4
Oct 17 '13 at 21:52
source share



All Articles