How to subtract a month from Date object?

前端 未结 4 1872
名媛妹妹
名媛妹妹 2021-02-06 23:48

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

相关标签:
4条回答
  • 2021-02-07 00:30

    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.

    0 讨论(0)
  • 2021-02-07 00:32

    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()
    
    0 讨论(0)
  • 2021-02-07 00:33
    Dim d As DateTime = #1/1/2010#
    d = d.AddMonths(-1)
    
    0 讨论(0)
  • 2021-02-07 00:39

    I have used the following and it works.

    Dim dtToday As DateTime = Date.Today
    dtToday = dtToday.AddMonths(-2)
    
    0 讨论(0)
提交回复
热议问题