Reputation: 6778
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"
Upvotes: 0
Views: 5580
Reputation: 1503859
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.
Upvotes: 7