我有一个类似下面的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运行时。见下面的消息
如果我将生效日期更改为AddDays(3),它将再次开始工作。但我想更可靠地解决它
api_reqBody["effectiveDate"] = DateTime.Today.AddDays(3).ToString(Helper.DATE_FORMAT_API);
答案 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的一些重载。