Is there a safe check I can do before calling DateTime.AddMonths(int months)?
If I call AddMonths on a DateTime object using an int that is too large, I get an Argumen开发者_如何转开发tException thrown in my face with a polite message that says,
"The added or subtracted value results in an un-representable DateTime. Parameter name: months"
What check should I do on the months argument before calling this method?
From the MSDN:
ArgumentOutOfRangeException
The resulting DateTime is less than MinValue or greater than MaxValue.
-or-
months is less than -120,000 or greater than 120,000.
Based on your comment I'd say that the resultant months value is greater than 120,000.
You could get total months in the current date time and check that that plus your value isn't out of range, or catch the exception as others have suggested.
Wrap the AddMonths
method in a try
block if you're anticipating such a problem.
For anyone else that ends up here, and like me, didn't like the accepted answer because, as the comments say, you're kind of doing half the work that the DateTime methods are meant to do, and also want to avoid the whole try-catch thing...
Instead, you can take the Min/Max value you're expecting to hit and work backwards from there:
DateTime myDate;
if (DateTime.MaxValue.AddMonths(-2) < myDate) {
// it'll overflow
} else {
// I can safely add two months to myDate
}
As I one-liner, in my circumstance, I ended up with:
toDate = DateTime.MaxValue.AddSeconds(-1) < fromDate ? DateTime.MaxValue : fromDate.AddSeconds(1);
精彩评论