MATLAB: Calculating the difference between 2 dates

dates

Dear all,
I would like to calculate the difference between the dates say,
20/11/08 and 12/10/2011 in weeks and in months
cheers

Best Answer

numdays = datenum('12/10/2011') - datenum('20/11/08');
numweeks = numdays / 7; %and round() or floor() or ceil() as appropriate
numdaysvec = datevec(numdays);
nummonths = numdaysvec(1) * 12 + numdaysvec(2) - 1;
Note that you might have to give datenum() a hint as to whether the first date is the 11th month of 2008 or the 8th month of 2011.
Also, I used a shortcut here of converting the day offset as if it was a date relative to "year 0". MATLAB has weak leap-year routines that believe that "year 0" was a leap year. More accurate would be to datevec() the original dates and do modular arithmetic.
Oh yes, you also need to decide whether dates in the same month count as "0 months" or as "1 month" for your purposes.