26

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?

Andrew
  • 11,068
  • 17
  • 52
  • 62
  • 1
    OK. This question (and the answers) are really, really confusing me. What is the exact code you are using that exhibits the above problem? I typed Today.AddMonths(-1) into the debugger and it works properly, subtracting one from the year if you are in January. – Jason Berkan Feb 03 '10 at 19:34
  • 2
    Hi Jason. The problem wasn't actually that .AddMonths() wasn't working. The problem was that Date objects are immutable. I hadn't assigned the return value of .AddMonths() to a variable. For example, I was doing someDate.AddMonths(-1), when it should be someDate = someDate.AddMonths(-1). – Andrew Feb 03 '10 at 21:53
  • 2
    In that case, though, someDate would not change. i.e. in your example, it would still be set to 01-Jan-2010, not 01-Dec-2010. Hence, my confusion. – Jason Berkan Feb 04 '10 at 00:12

4 Answers4

44

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()
Joel Etherton
  • 37,325
  • 10
  • 89
  • 104
8

This works fine, you need to remember that the DateTime is imutable.

Dim d As DateTime
d = New DateTime(2010, 1, 1)
d = d.AddMonths(-1)

Have a look at DateTime Structure

A calculation on an instance of DateTime, such as Add or Subtract, does not modify the value of the instance. Instead, the calculation returns a new instance of DateTime whose value is the result of the calculation.

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
2
Dim d As DateTime = #1/1/2010#
d = d.AddMonths(-1)
dbasnett
  • 11,334
  • 2
  • 25
  • 33
1

I have used the following and it works.

Dim dtToday As DateTime = Date.Today
dtToday = dtToday.AddMonths(-2)
Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
ksk
  • 311
  • 1
  • 8