Subtract months from a given date in Matlab

Maddy picture Maddy · Mar 11, 2011 · Viewed 7.1k times · Source

I need to subtract 21 months from a given date.

My solution as given below only takes me to the first month of the given year :(

[a,b,c]= datevec(date);
b= b-21;
datestr(datenum(a,b,c)) %--> 11-Jan-2011 (WRONG).

I want the answer to be 11-June-2009.

Answer

Gareth McCaughan picture Gareth McCaughan · Mar 11, 2011

Go via date numbers rather than date vectors and use addtodate:

>> d = datenum(date);
>> e = addtodate(d, -21, 'month');
>> datestr(e)

ans =

11-Jun-2009