dates between two limits

조회 수: 1 (최근 30일)
Ishak Oussama
Ishak Oussama 2019년 2월 9일
편집: YT 2019년 2월 9일
Hi, I want to make a script between start_date to end_date with the following conditions
for example start_date = '20190131'
end_date ='20190205'
so what I want ,
start_date(1:4) must consist of 4 digits
start_date(5:6) should only take values ​​between 1 and 12
start_date(7:8) should only take values ​​between 1 and 31 and same thing for end_date
if my conditions are right it will run my program otherwise it will show me wrong date.

답변 (1개)

YT
YT 2019년 2월 9일
편집: YT 2019년 2월 9일
I came up with 2 options:
OPTION 1
clear;
start_date = '20190131';
end_date = '20191205';
myFormat = 'yyyyMMdd';
DateStrings = {start_date; end_date};
t = datetime(DateStrings,'InputFormat',myFormat);
if(~isnat(t))
disp('Everything OK');
else
disp(['Wrong string: ' strjoin((DateStrings(isnat(t))),', ')]);
end
Now option 1 works pretty good, but if you input a wrong day number, datetime will throw an error and it does not specify which of the strings (start_date / end_date) was wrong.
OPTION 2
It may seem a bit "spaghettified", but you have to wrap both the start and end date seperatly in a try/catch statement if you really want to let the user know which one of the dates was wrong.
clear;
start_date = '20190131';
end_date = '20191205';
myFormat = 'yyyyMMdd';
try
tStart = datetime(start_date,'InputFormat',myFormat);
catch
error(['Unable to convert `' start_date '` to datetime using the format `' myFormat '`']);
end
try
tEnd = datetime(end_date,'InputFormat',myFormat);
catch
error(['Unable to convert `' end_date '` to datetime using the format `' myFormat '`']);
end
if (~isnat(tStart) && ~isnat(tEnd)) %check once more if dates are valid (yes this is necessary)
disp('Dates are valid!');
else
if(isnat(tStart))
error(['Input `' start_date '` invalid datetime format. Correct format is `' myFormat '`.']);
elseif(isnat(tEnd))
error(['Input `' end_date '` invalid datetime format. Correct format is `' myFormat '`.']);
end
end

카테고리

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

제품


릴리스

R2014b

Community Treasure Hunt

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

Start Hunting!

Translated by