2012-05-21 77 views
0

我有一組數據['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']Month in Matlab

我該怎麼做?另外我該如何計算不。在Matlab中的兩個日期之間的月份?

回答

5

首先,我希望我不會在這裏假設太多,但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