How to I validate a string to ensure it contains a valid Date .

조회 수: 45 (최근 30일)
Matt O'Brien
Matt O'Brien 2023년 3월 11일
편집: Stephen23 2023년 3월 11일
I know how to convert a string to a date...... but how do I validate if the string is a valid date.
Example
MyStr = '23max2023'; % invalid may typo max
infmt = "ddMMMyyyy";
MyDate = datetime(MyStr,"InputFormat",infmt)
This generates an error if invalid.... is there an elegant method to check if a date is valid without having to generate an error and checking the type of error.

답변 (1개)

the cyclist
the cyclist 2023년 3월 11일
편집: the cyclist 2023년 3월 11일
Here is one way:
MyStr = '23max2023'; % Invalid string will give an empty array
isMyDateFormat = regexp(MyStr, '\d{2}(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d{4}')
isMyDateFormat = []
MyStr = '23may2023'; % Valid string will give a 1
isMyDateFormat = regexp(MyStr, '\d{2}(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d{4}')
isMyDateFormat = 1
This method specifically check for the pattern of exactly 2 digits, then a lower-case standard month abbreviation, then exactly 4 digits. One could get even more sophisticated if needed.
Alternatively, you could wrap your code in a try-catch structure, to try the datetime command, then do something else if it fails:
MyStr = '23max2023';
infmt = "ddMMMyyyy";
try
MyDate = datetime(MyStr,"InputFormat",infmt)
catch
fprintf("Invalid date format")
end
Invalid date format
  댓글 수: 8
Matt O'Brien
Matt O'Brien 2023년 3월 11일
Thank you. I will use this approach. I understand and agree with the approach of not re-engineering a date validation function.
To me, a recent MatLab coder, it is staggering to think that the following format does not exist...
[ MyDateVal, MyDateStatus] = datetime(.............
Anyway...I will use the try ... catch syntax.
All feedback appreciated.
I need to figure out how to flag this to be the correct answer.
Steven Lord
Steven Lord 2023년 3월 11일
To me, a recent MatLab coder, it is staggering to think that the following format does not exist...
[ MyDateVal, MyDateStatus] = datetime(.............
If datetime behaved that way instead of throwing an error, every single call to datetime would need to be followed by an if call checking that MyDateStatus indicated success before proceeding to use MyDateVal. With the error-based approach, as long as the next line runs the datetime call succeeded.
I wouldn't want to see code that was forced to look like the following, to take the "return result and status" pattern to the extreme:
x = 1:10;
y = 11;
[result, didSucceeed] = plus(x, y);
if ~didSucceed % We couldn't add x and y
% handle the error
end
IMO better to just let plus (or datetime) throw the error itself. The function has more information about what exactly went wrong, so it may be able to distinguish between the "you gave me a month name I didn't recognize but that could be a valid month name in a different locale" and "your data doesn't match the format you asked for at all" cases and provide more specifically tailored messages.

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

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by