如何修复C#中未来日期引发的ArgumentOutOfRangeException异常
Let's break down exactly why your code is throwing that error, then implement a reliable fix that handles all edge cases.
The Root Cause
When your code runs on May 29th, DateTime.Today.AddDays(2) sets effectiveDate to May 31st. Then you attempt to create a new date using:
- Year:
effDate.Year + 5(e.g., 2024 → 2029) - Month:
effDate.Month(5 for May) - Day:
effDate.Day + 1(31 → 32)
Since May only has 31 days, new DateTime(2029, 5, 32) is an invalid date—this is exactly what triggers the ArgumentOutOfRangeException. When you switch to AddDays(3), effectiveDate becomes June 1st, so Day +1 equals 2 (a valid day for June), which is why that works temporarily.
The Reliable Fix
Instead of manually constructing a DateTime object (which doesn't handle date overflow or edge cases like leap years), use C#'s built-in AddYears() and AddDays() methods. These methods automatically adjust dates to valid values, so you don't have to worry about month lengths or leap years.
Here's the corrected code:
// Value of effective date api_reqBody["effectiveDate"] = DateTime.Today.AddDays(2).ToString(Helper.DATE_FORMAT_API); // Calculate maturity date safely var effDate = Convert.ToDateTime(api_reqBody["effectiveDate"]); var maturityDate = effDate.AddYears(uServiceSupport.H300IORIL_MAXTERM_YEARS) .AddDays(1); api_reqBody["updatedLoanAccount"]["maturityDate"] = maturityDate.ToString(Helper.DATE_FORMAT_API);
Why This Works
AddYears(5)handles leap year adjustments automatically: ifeffDatewas February 29th, it would adjust to February 28th (or March 1st in some contexts) for non-leap years.AddDays(1)safely moves to the next day, even if the original date was the last day of the month (e.g., May 31st → June 1st, December 31st → January 1st of the next year).
This approach is far more robust than manual date construction, as it covers all edge cases you might encounter (like different month lengths, leap years, end-of-year dates) without extra code.
内容的提问来源于stack exchange,提问作者Priyanka Ray

