MATLAB Answers

0

dates between two limits

Mustapha Messaoud さんによって質問されました 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.

  0 件のコメント

サインイン to comment.

製品


リリース

R2014b

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

  0 件のコメント

サインイン to comment.



Translated by