Why is AddMonths () not working in my DateTime? (see code)
Controller:
DateTime startDate = DateTime.Now;
ViewData["now"] = startDate.ToString();
ViewData["interval"] = interval.ToString();
startDate.AddMonths(interval);
ViewData["later"] = startDate.ToString();
View:
Now: <%=ViewData["now"] %><br />
Later: <%=ViewData["later"] %><br />
Interval: <%=ViewData["interval"] %>
This gives:
Now: 10/2/2009 12:17:14 PM
Later: 10/2/2009 12:17:14 PM
Interval: 6
startDate = startDate.AddMonths(interval);
From the documentation:
This method does not change the value of this DateTime object. Instead, a new DateTime object is returned whose value is the result of this operation.
Do you really want:
ViewData ["later"] = startDate.AddMonths (int) .ToString ();
or something like that.
AddMonths returns a new DateTime value with a value.
startDate = startDate.AddMonths(interval)
you need to assign the result to a AddMonths
variable. AddMonths
does not change the value of the object it was called on, but returns a new one DateTime
with a value that is the result of an operation that leaves the original value unchanged DateTime
.