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!