Identifying errors in datetime input strings

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 件のコメント

Stephen23
Stephen23 2023 年 5 月 11 日
編集済み: Stephen23 2023 年 5 月 11 日
"Is there any way to check that the input string corresponds to a date or not"
Of course, but it depends on how broad you want to check the input data:
Can the values be negative as well?
Can the months also be out of range?
Can non-digit characters occur?
phenan08
phenan08 2023 年 5 月 11 日
編集済み: phenan08 2023 年 5 月 12 日
Then, based on Star Strider's proposal, I assume that you just have to check the following command as well:
test = 1 <= str2double(flds(2)) & str2double(flds(2)) <= 12
Before that, the input string format can be checked using the following command:
test = matches(string(str),digitsPattern(2)+"/"+digitsPattern(2)+"/"+digitsPattern(4))
Thank you Stephen23 for having permitted to share a deeper approach of the present problem.

サインインしてコメントする。

 採用された回答

Star Strider
Star Strider 2023 年 5 月 11 日
編集済み: Star Strider 2023 年 5 月 11 日

1 投票

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,'/')
flds = 1×3 string array
"32" "05" "2022"
dmax = eomday(str2double(flds(3)),str2double(flds(2)))
dmax = 31
Check = 1 <= str2double(flds(1)) & str2double(flds(1)) <= dmax
Check = logical
0
So in this instance, the day value is not appropriate.
.

2 件のコメント

phenan08
phenan08 2023 年 5 月 11 日
Good job, Star Strider! Thank you very much.
Star Strider
Star Strider 2023 年 5 月 11 日
As always, my pleasure!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeShifting and Sorting Matrices についてさらに検索

製品

リリース

R2023a

質問済み:

2023 年 5 月 11 日

編集済み:

2023 年 5 月 12 日

Community Treasure Hunt

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

Start Hunting!

Translated by