calculating the difference between 2 dates

조회 수: 63 (최근 30일)
antonet
antonet 2012년 5월 25일
댓글: Rosanna 2018년 10월 11일
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

채택된 답변

Walter Roberson
Walter Roberson 2012년 5월 25일
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
Walter Roberson
Walter Roberson 2012년 5월 26일
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
antonet 2012년 5월 26일
Thank you!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Andy
Andy 2018년 3월 13일
편집: Andy 2018년 3월 13일
there's something better now since 2014 release I believe:
w = between(startRange,endRange,'weeks')
y = between(startRange,endRange,'years')
m = between(startRange,endRange,'months')
  댓글 수: 2
Peter Perkins
Peter Perkins 2018년 3월 15일
Indeed:
>> between(datetime('20-Nov-2008'),datetime('12-Oct-2011'),{'weeks' 'months'})
ans =
calendarDuration
34mo 3w
Rosanna
Rosanna 2018년 10월 11일
Hi all I have to compute the occurrence time (days from the starting date) of a large number (eg N=1000) of events, for which I have the Year, Month, Day, Hour, Minute in numerical format (eg 2008, 05, 23, 08, 34). How can I proceed? Thanks Rosanna

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by