简体   繁体   中英

How to fix ArgumentOutOfRangeException for a future date in C#

I have a C# code like below for date time handling and want to know how can I fix it.

//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 .

I am getting an ArgumentOutOfRangeException for date time handling for the above code - when its ran today on 29/05 . See message below 在此处输入图片说明

If I change the effective date to be AddDays(3) , it starts working again. But I want to fix it more reliably
api_reqBody["effectiveDate"] = DateTime.Today.AddDays(3).ToString(Helper.DATE_FORMAT_API);

The proper way to add periods of time to a DateTime object is to use the Add methods. So in your case you would use AddYears first, then 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);

This isolates you from nuisances such as the number of days per month, leap years, etc.

effDate.Day + 1 in your code is 32, since effDate date is the 31th May. There's no month with 32 days. Use AddDays or some overload of DateTime + TimeSpan instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM