Search code examples
matlabdatedate-math

Subtract months from a given date in Matlab


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.


Solution

  • 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