MATLAB: How to calculate the difference between dates when the date is in the yyyy-mm-dd format

datedatenumdatevecMATLAB

I have dates in the following format :
date=20070123
date2=20070138
I would like to be able to calculate the number of days between the two.

Best Answer

The function DATENUM in MATLAB allows the conversion of various date formats to a serial date number. Date can essentially be expressed in three formats in MATLAB . They are :
Date String: '24-Oct-2003 12:45:07'
Date Vector: [2003 10 24 12 45 07]
Serial Date Number: 7.3188e+005
In order to be able to subtract dates the "Serial Date Number" format is the most useful. It essentially returns the number of days that have elapsed after an arbitrary start date ( the default is Jan 01 0000, but this can be set to any date you prefer).
For example if one wanted to find the number of days between 02/01/2007 and 04/13/2008, the following example could be used
firstdate = datenum(2007,02,01); % note year,month,day
seconddate= datenum(2007,04,13);
diff_date =abs(firstdate -seconddate);
The input would need to modified to work with DATENUM in the following manner
temp1=num2str(date2)
temp2=strcat(temp1(1:4),'.',temp1(5:6),'.',temp1(7:8))
res = datenum(temp2,'yy.mm.dd')
Related Question