Reputation: 43813
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 yields:
Now: 10/2/2009 12:17:14 PM
Later: 10/2/2009 12:17:14 PM
Interval: 6
Upvotes: 3
Views: 4536
Reputation: 19214
you need to assign the result of the AddMonths
to a variable. AddMonths
does not change the value of the object it was called on, but rather returns a new DateTime
with the value that results from the operation leaving the original DateTime
value unchanged.
Upvotes: 3
Reputation: 820
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.
You really want:
ViewData["later"] = startDate.AddMonths(interval).ToString();
or something like that.
Upvotes: 5
Reputation: 7778
AddMonths returns a new DateTime with the value.
startDate = startDate.AddMonths(interval)
Upvotes: 3