首先,我希望我不會在這裏假設太多,但MATLAB已經內置在Date and Time Operations,如果你還沒有使用,你應該開始使用。
有三種方式來表示時間(如直接從DOC)
Date String: '24-Oct-2003 12:45:07'
Date Vector: [2003 10 24 12 45 07]
Serial Date Number: 7.3188e+005
有一個叫datevec
功能,如果你能得到您的日期,這個日期矢量格式,那麼很容易計算個月的兩個日期之間的數:
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
上面代碼使用datenum
,以檢查是否DATE1比DATE2(或反之亦然)更大
此外,如果您只想顯示月份和年份,則可以指定如何顯示日期字符串datestr
>> date1
date1 =
2004 6 17 0 0 0
>> datestr(date1,'mm/yyyy') %Displays just month and year
ans =
06/2004