Identifying errors in datetime input strings
3 次查看(过去 30 天)
显示 更早的评论
During application development using appdesigner, I want to check that an input string is a time object or not.
As an example, a correct string input does not generate any errors:
str = "31/05/2022" ;
datetime(str,"Format","dd/MM/uuuu")
which returns:
ans =
datetime
31/05/2022
However, when the input string does not match with a true date, then an error follows:
str = "32/05/2022" ;
datetime(str,"Format","dd/MM/uuuu")
Error using datetime
Unable to convert '32/05/2022' to datetime using the format 'dd/MM/uuuu'.
Is there any way to check that the input string corresponds to a date or not, without generating any errors? I intend to compile the code at the end of the project, so I cannot use the try catch statements, since they were not supported by MATLAB Coder up to now (which is a bit of a shame, considering the prices of the coder and the compiler...).
Any suggestion to deal with that issue?
2 个评论
采纳的回答
Star Strider
2023-5-11
编辑:Star Strider
2023-5-11
If you already know the date fields for day, month, and year, one approach would be to use the eomday function to determine the maximum number of days in a month for the matching month and year —
str = "32/05/2022" ;
flds = strsplit(str,'/')
dmax = eomday(str2double(flds(3)),str2double(flds(2)))
Check = 1 <= str2double(flds(1)) & str2double(flds(1)) <= dmax
So in this instance, the day value is not appropriate.
.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!