我有一组日期 ['1/7/1993';'4/21/1993';'6/11/1993';'2/7/1994';'5/26/1994';'3/ 15/1995'],并希望将其转换为格式为“mm/yyyy”的日期数组,其中包含最小和最大日期内的所有月份和年份,即 datr = ['1/1993';'2/ 1993';'3/1993';.......;'3/1995']
我该怎么做?另外我如何计算编号。Matlab中两个日期之间的月份?
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