如何修复C#中未来日期的ArgumentOutOfRangeException

时间:2018-05-29 07:23:07

标签: c# .net

我有一个类似下面的C#代码用于日期时间处理,并想知道如何解决它。

//Value of effective date 
api_reqBody["effectiveDate"] = DateTime.Today.AddDays(2).ToString(Helper.DATE_FORMAT_API);

//Value of Maturity date 
var effDate = Convert.ToDateTime(api_reqBody["effectiveDate"]);
api_reqBody["updatedLoanAccount"]["maturityDate"] =
            new DateTime(effDate.Year + uServiceSupport.H300IORIL_MAXTERM_YEARS, effDate.Month, effDate.Day + 1).ToString(Helper.DATE_FORMAT_API);      
// Value of H300IORIL_MAXTERM_YEARS is 5 .

我收到一个ArgumentOutOfRangeException,用于上述代码的日期时间处理 - 当它今天在29/05运行时。见下面的消息 enter image description here

如果我将生效日期更改为AddDays(3),它将再次开始工作。但我想更可靠地解决它 api_reqBody["effectiveDate"] = DateTime.Today.AddDays(3).ToString(Helper.DATE_FORMAT_API);

2 个答案:

答案 0 :(得分:4)

DateTime对象添加时间段的正确方法是使用Add方法。因此,在您的情况下,您首先使用AddYears,然后使用AddDays

api_reqBody["updatedLoanAccount"]["maturityDate"] =
  new DateTime(effDate.Year, effDate.Month, effDate.Day)
  .AddYears(uServiceSupport.H300IORIL_MAXTERM_YEARS)
  .AddDays(1)
  .ToString(Helper.DATE_FORMAT_API);

这使您免受诸如每月的天数,闰年等的滋扰。

答案 1 :(得分:1)

代码中的

effDate.Day + 1为32,因为effDate日期是5月31日。 32天没有月份。请改为使用AddDays或DateTime + TimeSpan的一些重载。