You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复C#中未来日期引发的ArgumentOutOfRangeException异常

Fix for ArgumentOutOfRangeException in C# Date Calculation

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: if effDate was 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:50:40