Error check on dates

조회 수: 1 (최근 30일)
Alexandra Philip
Alexandra Philip 2020년 7월 2일
답변: Monisha Nalluru 2020년 7월 9일
I am having some trouble with developing an error check for the format of dates being inputted by the user.
I first use:
Testdate=input('What is the test date?(mm-dd-yyyy)','s')
Teststr=convertCharsToStrings(Testdate);
TestT=ERRORT(Teststr);
I am able to obtain the user's input, I then would like to create a new function such as:
function Teststr=ERRORT(Teststr)
With this function, I would like to create an error checking code to ensure the user inputs the date in the format mm-dd-yyyy and also using reasonable numbers for month, day, and year(such as month: from 1 to 12, day: from 1 to 31, year: from 1900 to 2020). So, if the user doesn't input such values, an input message regarding their error will appear.
Any suggestions?
  댓글 수: 1
dpb
dpb 2020년 7월 2일
편집: dpb 2020년 7월 2일
You pretty-much defined what can test for, start writing... :)
A try...catch...end block on the datetime code to translate is a good fallback.
You really can't prevent the user from reversing mm/dd -- dd/mm for those that have possible interpretation as either -- you could ask for letter string for month instead...or, there is a widget uidatepicker that might make your job easier...
Alternatively, altho the user may get tired of it very quickly, you could display the date as interpreted and ask fof confirmation it's what was intended.

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

답변 (1개)

Monisha Nalluru
Monisha Nalluru 2020년 7월 9일
From my understanding, you want to check whether the given date is valid, and it falls in range (1990 and 2020).
You can make use of datetime function which takes valid dates from string format
Inorder to check whether it falls in required range, compare the date (which is allowed in MATLAB)
You can use something like below:
Testdatestr=input('What is the test date?(mm-dd-yyyy)','s');
function output=ERRORT(Testdatestr)
Testdate=datetime(Testdatestr,'InputFormat','MM-dd-yyyy'); % Throws error when date is not valid
mindate=datetime('01-01-1990','InputFormat','MM-dd-yyyy');
maxdate=datetime('now');
if Testdate>=mindate && Testdate<=maxdate
output=Testdate;
else
error('date is not in valid range'); % Throws error when date is not in given range
end
end
Hope this helps!

카테고리

Help CenterFile Exchange에서 Time Series Objects에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by