Question

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
Was it helpful?

Solution

startDate  = startDate.AddMonths(interval);

OTHER TIPS

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.

AddMonths returns a new DateTime with the value.

startDate = startDate.AddMonths(interval)

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top