0

In C# I have from and to DateTime vales and want to check whether a value DateTime is within the range, how can I do this?

lowerBound = "01-Dec-2011 09:45:58"
upperBound = "01-Dec-2011 09:38:58"
value = "01-Dec-2011 09:49:58"
Chris Fulstow
  • 39,861
  • 10
  • 85
  • 109
shamim
  • 6,390
  • 20
  • 77
  • 143
  • http://stackoverflow.com/questions/2553663/how-to-determine-if-birthday-or-anniversary-occured-during-date-range – giftcv Dec 01 '11 at 06:23

1 Answers1

7

Just use the comparison operators as you would for numbers:

DateTime lowerBound = new DateTime(2011, 12, 1, 9, 38, 58);
DateTime upperBound = new DateTime(2011, 12, 1, 9, 49, 58);
DateTime value = new DateTime(2011, 12, 1, 9, 45, 58);

// This is an inclusive lower bound and an exclusive upper bound.
// Adjust to taste.
if (lowerBound <= value && value < upperBound)

You'll need to be careful that the values are all the same "kind" (UTC, local, unspecific). If you're trying to compare instants in time, (e.g. "did X happen before Y") it's probably best to use UTC.

Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049