Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

calculating the difference between 2 dates

Asked by antonet on 25 May 2012

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

0 Comments

antonet

Tags

Products

No products are associated with this question.

1 Answer

Answer by Walter Roberson on 25 May 2012
Accepted 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.

4 Comments

antonet on 26 May 2012

i think it should be

numdays = datenum({'02/11/08'},'dd/mm/yy') - datenum({'09/10/11'},'dd/mm/yy')

Walter Roberson on 26 May 2012

Your date '20/11/08' is ambiguous. MATLAB is guessing incorrectly about the format it is in. You should be telling MATLAB the format when you datenum() the string. http://www.mathworks.com/help/techdoc/matlab_prog/bspgcx2-1.html#bsplnu3-2

datenum('20/11/08', 'dd/yy/mm') or datenum('20/11/08', 'dd/mm/yy') as appropriate

antonet on 26 May 2012

Thank you!

Walter Roberson

Contact us