Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 4th, 2012  |  syntax: None  |  size: 1.20 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to know if a DateTime is between a DateRange in C#
  2. // The date range
  3. DateTime startDate;
  4. DateTime endDate;
  5.  
  6. DateTime dateToCheck;
  7.        
  8. return dateToCheck >= startDate && dateToCheck < endDate;
  9.        
  10. public interface IRange<T>
  11. {
  12.     T Start { get; }
  13.     T End { get; }
  14.     bool Includes(T value);
  15.     bool Includes(IRange<T> range);
  16. }
  17.  
  18. public class DateRange : IRange<DateTime>        
  19. {
  20.     public DateRange(DateTime start, DateTime end)
  21.     {
  22.         Start = start;
  23.         End = end;
  24.     }
  25.  
  26.     public DateTime Start { get; private set; }
  27.     public DateTime End { get; private set; }
  28.  
  29.     public bool Includes(DateTime value)
  30.     {
  31.         return (Start <= value) && (value <= End);
  32.     }
  33.  
  34.     public bool Includes(IRange<DateTime> range)
  35.     {
  36.         return (Start <= range.Start) && (range.End <= End);
  37.     }
  38. }
  39.        
  40. DateRange range = new DateRange(startDate, endDate);
  41. range.Includes(date)
  42.        
  43. return (dateTocheck >= startDate && dateToCheck <= endDate);
  44.        
  45. public static class DateTimeExtensions
  46. {
  47.     public static bool InRange(this DateTime dateToCheck, DateTime startDate, DateTime endDate)
  48.     {
  49.         return dateToCheck >= startDate && dateToCheck < endDate;
  50.     }
  51. }
  52.        
  53. dateToCheck.InRange(startDate, endDate)