Reputation: 75
I have an array of dates ['1/7/1993';'4/21/1993';'6/11/1993';'2/7/1994';'5/26/1994';'3/15/1995'], and want to covert it into an array of dates with format 'mm/yyyy' with all the months and years within the minimum and maximum date included, i.e. datr = ['1/1993';'2/1993';'3/1993';.......;'3/1995']
How can I do it? Also how do I calculate the no. of months between two dates in Matlab?
Upvotes: 0
Views: 3808
Reputation: 1623
First, I hope I'm not assuming too much here but MATLAB has built in Date and Time Operations that if you aren't already using, you should start using.
There are three ways to represent dates (as straight from the doc)
Date String: '24-Oct-2003 12:45:07'
Date Vector: [2003 10 24 12 45 07]
Serial Date Number: 7.3188e+005
There is a function called datevec
, and if you can get your dates into this Date Vector format then it is easy to compute the number of months between two dates:
date1 = datevec('17-jun-04', 'dd-mmm-yy')
date2 = datevec('24-oct-03', 'dd-mmm-yy')
% This if/else checks which date is later than the other
if(datenum(date1) > datenum(date2))
% num months is the number of months left in date2's year (ex. 2 months)+
% the number of months in date1's year (ex. 6 months) +
% the number of months in the years between (ex. 0 months).
num_months = (12 - date2(2)) + date1(2) + 12*(date1(1)-date2(1)-1)
else
%just flipped date1 and date2 from the above.
num_months = (12 - date1(2)) + date2(2) + 12*(date2(1)-date1(2)-1)
end
The above code uses datenum
to check if date1 is greater than date2 (or vice versa)
Also, if you want to display just the month and years, you can specify how to display a date string with datestr
>> date1
date1 =
2004 6 17 0 0 0
>> datestr(date1,'mm/yyyy') %Displays just month and year
ans =
06/2004
Upvotes: 5