- Are you rounding to the earliest day? For example, should 12/1/2019 23:59:59 be treated as 12/1/2019 00:00:00 ?
- Just to be clear, from the values you shared, the number of days should be [1; 0; 1; 0; 0; 0] ?
How to calculate date length between 2 dates
3 次查看(过去 30 天)
显示 更早的评论
For the below data, I would like to count the date length between Conf.Time with Trade date
In excel, you can easily do it by using function: weekday(trade date, conftime, holiday), how do you do this in Matlab?
1 个评论
Adam Danz
2020-7-1
采纳的回答
Adam Danz
2020-7-1
Replace 'data' with your datetime values in string format. If your datetime values are already in datetime format, replace 'dt' with your datetime values. They must be in a nx3 array or you'll have to make some slight changes.
See inline comments for details.
data = {
'12/17/2019' '12/20/2019' '12/18/2019 23:47:30'
'12/04/2019' '12/05/2019' '12/04/2019 23:48:02'
'12/17/2019' '12/20/2019' '12/18/2019 23:47:30'
'12/27/2019' '12/30/2019' '12/27/2019 23:47:44'
'12/03/2019' '12/04/2019' '12/03/2019 23:43:01'
'12/27/2019' '12/30/2019' '12/27/2019 23:47:44'
};
dt = [datetime(data(:,1:2),'InputFormat','MM/dd/yyyy'), ...
datetime(data(:,3),'InputFormat','MM/dd/yyyy HH:mm:ss')];
% Round all datetime values to their earliest date (is this your intension?)
dt = dateshift(dt,'start','day');
% Compute number of days between col 3 and col 1
nDays = days(dt(:,3)-dt(:,1));
% Determine if any days are weekends
nWeekends = arrayfun(@(i)sum(isweekend(dt(i,1):day(1):dt(i,3))), 1:size(dt,1))';
% Subtract weekends
nWeekdays = nDays - nWeekends;
% Determine if any days are holidays
% List holidays to exclude.
% You could also use the holidays() function but that would list all holidays
% within range, not only the ones you specified.
% For example, holidayList = holidays(min(dt(:,1)), max(dt(:,3)));
holidayList = {'12/24/2019','01/01/2020'};
holidayListdt = datetime(holidayList,'InputFormat','MM/dd/yyyy');
nHolidays = arrayfun(@(i)sum(isbetween(holidayListdt,dt(i,1),dt(i,3))), 1:size(dt,1))';
% subtract number of holidays
nWeekdays_noHolidays = nWeekdays - nHolidays;
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Calendar 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!