tags:

views:

131

answers:

4

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
+15  A: 
startDate  = startDate.AddMonths(interval);
dove
This is correct. Operations on DateTimes are non-destructive.
Stuart Branham
+3  A: 

AddMonths returns a new DateTime with the value.

startDate = startDate.AddMonths(interval)
ongle
+5  A: 

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.

M1EK
+3  A: 

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.

NerdFury