How to subtract a month from Date object?

Andrew picture Andrew · Feb 3, 2010 · Viewed 56.5k times · Source

How do I subtract a month from a date object in VB.NET?

I have tried:

Today.AddMonths(-1)

However, given that Today is 01-Jan-2010, the result I get is 01-Dec-2010. The answer I want is 01-Dec-2009.

Is there a convenient way of doing this within the .NET framework?

Answer

Joel Etherton picture Joel Etherton · Feb 3, 2010

You actually have to transport Today into a variable and let that assignment work there. The following code will produce the result you expect (I just verified it because your post made me think twice).

Dim dt As DateTime = Date.Today
dt = dt.AddMonths(-2)

Dim x As String = dt.ToString()