필터 지우기
필터 지우기

Time difference in year between table datetime values and now

조회 수: 1 (최근 30일)
KAE
KAE 2024년 5월 22일
답변: Steven Lord 2024년 5월 22일
I have a vector of datetime values. I would like to get a vector of years elapsed between the datetime values and the present. How do I do this?
I tried
years(MyTable.BirthDate- now)
and got
Error using years
Input data must be a real, numeric array, or a duration array. Use YEAR to extract year numbers from a
datetime array.
I tried
year(MyTable.BirthDate- now)
but it rounded the values, and I would like the decimal difference. How can I get, for example, that one of the entries is 6.8 years old today?

채택된 답변

Steven Lord
Steven Lord 2024년 5월 22일
Don't use the now function. It returns a serial date number. Use datetime('now') (which returns a datetime) instead.
fiveYearsFromNow = datetime(2029, 5, 22)
fiveYearsFromNow = datetime
22-May-2029
N = datetime('now')
N = datetime
22-May-2024 21:18:40
y = years(fiveYearsFromNow-N)
y = 4.9970
But you may instead want to compute a calendarDuration instead of a duration. You can do this with the between function.
difference = between(N, fiveYearsFromNow) % Just shy of 5 years by timeofday(N)
difference = calendarDuration
4y 11mo 29d 2h 41m 19.759s
To correct for the fact that fiveYearsFromNow represents midnight on May 22, 2029 you can add timeofday(N) to it so fiveYearsFromNow and N represent the same amount of time past midnight on their respective days.
T = timeofday(N)
T = duration
21:18:40
difference = between(N, fiveYearsFromNow+T)
difference = calendarDuration
5y

추가 답변 (0개)

카테고리

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