How to I validate a string to ensure it contains a valid Date .
20 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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.
0 Kommentare
Antworten (1)
the cyclist
am 11 Mär. 2023
Bearbeitet: the cyclist
am 11 Mär. 2023
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}')
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}')
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
8 Kommentare
Steven Lord
am 11 Mär. 2023
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.
Siehe auch
Kategorien
Mehr zu Calendar finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!