MATLAB Answers

Checking the dates and times

5 views (last 30 days)
Alexandra Philip
Alexandra Philip on 21 Jul 2020
Answered: Adam Danz on 21 Jul 2020
I am having some trouble with developing code to see if the date inputted for the Testdate is one week old and if the date inputted for the Testdate isn't the current date for today should show an input for an error message to confirm the Testdate they inputted. So far I have:
Testdate=input('What is the test date?(dd-mm-yyyy)','s')
Teststr=convertCharsToStrings(Testdate);
TestT=ERRORT(Testdate);
Then here is the function with the error checking code:
if
Testdate=input('Confirm this test data: Y or N','s')
end
So I also would like if the user inputs Y, it continues to store the value and continue through the main script, but if inputs N, it allows the user to input a different Testdate to store.
Any suggestions or resolutions?

  2 Comments

Alexandra Philip
Alexandra Philip on 21 Jul 2020
Correction: If the test date is one week old from the current date today.
Alexandra Philip
Alexandra Philip on 21 Jul 2020
So far I have,
formatIn='mm/dd/yyyy'
if datenum(Testdate,formatIn)~=datenum('now')
Testdate=input('Confirm this test data: Y or N','s')
if Testdate=='N'
Testdate=input('Input the correct test date.','s')
end
end
within the function. However, this results in an error message:
Error using datenum (line 188)
DATENUM failed.
Error in ERRORT (line 4)
if datenum(Testdate,formatIn)~=datenum('now')
Error in Tumbleuser_final (line 7)
TestT=ERRORT(Testdate);
Caused by:
Error using datevec (line 218)
Failed to lookup month of year.
Any suggestions or resolutions?

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 21 Jul 2020
Why not use a UI such as
Using your method, the date should be converted to datetime
Testdate=input('What is the test date (dd-mm-yyyy)? ','s');
TestdateDT = datetime(Testdate,'InputFormat','dd-MM-yyyy');
Then test if the date is within 1 week (True/False) and is equal to today (True/False)
isWithinOneWeek = days((datetime('now') - TestdateDT)) <=7;
isToday = isequal(datetime('today'), TestdateDT);
If you want the user to continually enter a date until it obeys the rules, put that within a while loop.
Modify this to your needs
isWithinOneWeek = false;
while ~isWithinOneWeek
Testdate=input('What is the test date (dd-mm-yyyy)? ','s');
TestdateDT = datetime(Testdate,'InputFormat','dd-MM-yyyy');
isWithinOneWeek = days((datetime('now') - TestdateDT)) <=7;
end
One big flaw with this method is that it relys on the user to obey the command. For example, if the user uses slashes instead of dashes, you'll get an error: 21/07/2020.
This is why it's better to use more controlled methods of user input.

  0 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!