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

      

+2


source to share


4 answers


startDate  = startDate.AddMonths(interval);

      



+16


source


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.

+5


source


AddMonths returns a new DateTime value with a value.

startDate = startDate.AddMonths(interval)

      

+3


source


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

.

+3


source







All Articles