Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract a month from Date object?

Tags:

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?

like image 933
Andrew Avatar asked Feb 03 '10 04:02

Andrew


People also ask

How do you subtract date objects?

To subtract days to a JavaScript Date object, use the setDate() method. Under that, get the current days and subtract days.

How do I subtract a month from a date in Python?

The easiest way to subtract months from a date in Python is to use the dateutil extension. The relativedelta object from the dateutil. relativedelta module allows you to subtract any number of months from a date object.

How do I subtract a month from a date in SQL?

We can use DATEADD() function like below to Subtract Months from DateTime in Sql Server. DATEADD() functions first parameter value can be month or mm or m, all will return the same result.

How do pandas subtract months?

Subtract months from a date in Python using PandasPandas provide a class DateOffset, to store the duration or interval information. It is mostly used to increment or decrement a timestamp. It can be used with datetime module to to subtract N months from a date.


2 Answers

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() 
like image 105
Joel Etherton Avatar answered Sep 28 '22 04:09

Joel Etherton


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.

like image 28
Adriaan Stander Avatar answered Sep 28 '22 04:09

Adriaan Stander