I was wondering if there is any neat way to check is data is in allowed range. I mean in c# we can represent data from 0001-01-01 to (I think) 9999-01-01. However if we try to do something like that
DateTime result = DateTime.Parse("0001-01-01").Subtract(TimeSpan.FromDays(1))
I get an e开发者_运维知识库xception. Is there any neat way to check is it is possible to do DateTime operations (addition subtraction etc)
Just use the comparison operators (>, <, >=, <=, == and !=), as they are implemented in DateTime.
Example:
DateTime lowerAllowedDate = new DateTime(1,1,1); // 01/01/0001
DateTime upperAllowedDate = new DateTime(3000, 12, 31) // 31/12/3000
DateTime now = DateTime.Now
if (lowerAllowedDate <= now && now < upperAllowedDate)
{
//Do something with the date at is in within range
}
Consider these extension methods.
public static class ValidatedDateTimeOperations
{
public static bool TrySubtract (this DateTime dateTime, TimeSpan span, out DateTime result)
{
if (span < TimeSpan.Zero)
return TryAdd (dateTime, -span, out result);
if (dateTime.Ticks >= span.Ticks)
{
result = dateTime - span;
return true;
}
result = DateTime.MinValue;
return false;
}
public static bool TryAdd (this DateTime dateTime, TimeSpan span, out DateTime result)
{
if (span < TimeSpan.Zero)
return TrySubtract (dateTime, -span, out result);
if (DateTime.MaxValue.Ticks - span.Ticks >= dateTime.Ticks)
{
result = dateTime + span;
return true;
}
result = DateTime.MaxValue;
return false;
}
}
The can be called like this:
DateTime result;
if (DateTime.MinValue.TrySubtract (TimeSpan.FromDays(1), out result)
{
// Subtraction succeeded.
}
Checking for an overflow in a given operation beforehand is cumbersome and I'm not really sure it's really worth it against simply handling the exception
.
You could for example do the following when subtracting:
DateTime date;
TimeSpan subtractSpan;
if ((date - DateTime.MinValue) < subtractSpan)
{
//out of range exception: date - subtractSpan
}
Worth it? Your call.
Take a look at the DateTime structure documentation in MSDN.
In particular, you can take a look at:
- TryParse and TryParseExact
- The comparison operators
- MinValue and MaxValue
You can also put try..catch (ArgumentOutOfRangeException) around the DateTime values you are trying to use.
However, if you are consistently (or ever?) running into this kind of exception, I'd take a closer look at your design. Unless you are doing some serious date-crunching, I don't know of any instance where I would be bumping into the min and max values.
精彩评论