calculating the difference in dates
6 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Star Strider
on 13 Jul 2023
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 Comments
More Answers (1)
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.
0 Comments
See Also
Categories
Find more on Dates and Time in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!