MetaGuru
MetaGuru

Reputation: 43813

Why isn't AddMonths() working on 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 yields:

Now: 10/2/2009 12:17:14 PM
Later: 10/2/2009 12:17:14 PM
Interval: 6

Upvotes: 3

Views: 4536

Answers (4)

NerdFury
NerdFury

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

M1EK
M1EK

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

Donald Byrd
Donald Byrd

Reputation: 7778

AddMonths returns a new DateTime with the value.

startDate = startDate.AddMonths(interval)

Upvotes: 3

dove
dove

Reputation: 20674

startDate  = startDate.AddMonths(interval);

Upvotes: 19

Related Questions