views:

60

answers:

2

If I call AddMonths on a DateTime object using an int that is too large, I get an ArgumentException 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?

A: 

Wrap the AddMonths method in a try block if you're anticipating such a problem.

Mehrdad Afshari
+1  A: 

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.

ChrisF
The first point makes is pretty hard to detect. You'll have to basically calculate the resulting value yourself, in which case, why would you bother calling `AddMonth`?
Mehrdad Afshari
@Mehrdad - very true, so catching the exception might be the better way to go
ChrisF
Using (DateTime.MaxValue.Months + DateTime.MaxValue.Years * 12) to compare with the argument I'm using in AddMonths.
Corpsekicker