calculating the difference in dates

3 views (last 30 days)
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,

Accepted Answer

Star Strider
Star Strider on 13 Jul 2023
Try something like this —
T1 = readtable('dates.xlsx', 'VariableNamingRule','preserve')
T1 = 1929×3 table
Year Built Month Built equipment __________ ___________ __________ 2025 7 2.11e+05 2025 2 1.814e+05 2025 3 2.07e+05 2025 10 2.07e+05 2025 6 1.84e+05 2024 12 2.1066e+05 2025 2 2.1066e+05 2026 8 2.1e+05 2026 10 2.1e+05 2025 3 2.1e+05 2025 6 2.1e+05 2025 9 2.1063e+05 2025 12 2.1063e+05 2026 2 2.1063e+05 2026 4 2.1063e+05 1996 3 2.6802e+05
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'
T1 = 1929×4 table
Year Built Month Built equipment Years Difference __________ ___________ __________ ________________ 2025 7 2.11e+05 2.0014 2025 2 1.814e+05 1.5907 2025 3 2.07e+05 1.6674 2025 10 2.07e+05 2.2533 2025 6 1.84e+05 1.9193 2024 12 2.1066e+05 1.421 2025 2 2.1066e+05 1.5907 2026 8 2.1e+05 3.0856 2026 10 2.1e+05 3.2526 2025 3 2.1e+05 1.6674 2025 6 2.1e+05 1.9193 2025 9 2.1063e+05 2.1712 2025 12 2.1063e+05 2.4203 2026 2 2.1063e+05 2.5901 2026 4 2.1063e+05 2.7516 1996 3 2.6802e+05 -27.333
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.
.

More Answers (1)

Rahul
Rahul on 13 Jul 2023
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.

Community Treasure Hunt

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

Start Hunting!