calculating the difference in dates
조회 수: 5 (최근 30일)
이전 댓글 표시
Dear all,
I attach an excel that contains years and months.
For example the first row reads 2025 7. Today we have 2023 7
I want to calcute in years the difference between the attached dates and the current date (2023 7)
Is there a way to do that in matlab?
Also, I was wondering if it is possible to choose those equipment values that have life less than five years (<5) and life between 5 and 9 [5,9]
Best regards,
댓글 수: 0
채택된 답변
Star Strider
2023년 7월 13일
Try something like this —
T1 = readtable('dates.xlsx', 'VariableNamingRule','preserve')
YearMonth = datetime(T1{:,1},T1{:,2}, ones(size(T1{:,1}))); % Create 'datetime' Array
T1.('Years Difference') = years(YearMonth - datetime(2023,7,1)) % SUbtract Current Year & Month & Add Variable To 'T1'
The ‘Years Difference’ variable are in decimal fractions of years here. Getting them in units other than hours or days does not appear to be an option.
.
댓글 수: 0
추가 답변 (1개)
Rahul
2023년 7월 13일
Hi ektor,
You can try this code,
data = readtable('dates.xlsx');
years = data.YearBuilt;
months = data.MonthBuilt;
dates = datetime(years, months, 1);
currentDate = datetime('now');
yearsDiff = year(currentDate) - year(dates);
data.DifferenceInYears = yearsDiff;
writetable(data, 'updated_file.xlsx');
less_than_five = [];
for i = 1:length(data.YearBuilt)
if(data.DifferenceInYears(i)<5)
less_than_five = [less_than_five,data.equipment(i)];
end
end
between_five_and_nine = [];
for i = 1:length(data.YearBuilt)
if(data.DifferenceInYears(i)>5 && data.DifferenceInYears(i)<9)
between_five_and_nine = [between_five_and_nine,data.equipment(i)];
end
end
Please note that if the YearBuilt date is ahead of current DateTime, then it will be taken as negative. If you want it to be reverse or otherwise you can make the required changes to the yearsDiff variable line.
Hope this helps. Thanks.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!