How to calculate date length between 2 dates

조회 수: 2 (최근 30일)
Xueyi Li
Xueyi Li 2020년 7월 1일
편집: Xueyi Li 2020년 7월 2일
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
Adam Danz 2020년 7월 1일
  1. 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 ?
  2. Just to be clear, from the values you shared, the number of days should be [1; 0; 1; 0; 0; 0] ?

댓글을 달려면 로그인하십시오.

채택된 답변

Adam Danz
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;
  댓글 수: 5
Xueyi Li
Xueyi Li 2020년 7월 1일
Hi Adam,
Thanks a lot, it took quite a while to load the data but it eventually worked, thanks a lot!
Thanks!
You are the best!
Best regards,
Sherry
Adam Danz
Adam Danz 2020년 7월 1일
Glad I could help!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Calendar에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by