Datetime conversion from string with non-matching format does not yield an error
2 views (last 30 days)
Show older comments
Tracy Carla Rios Reyes
on 12 Feb 2021
I am reading in some data and want to check the format before converting. Interestingly, specifying the InputFormat with 4 digits while only having 2 digits does not yield an error, but rather trails the year with 00:
Reading in a date like
datetime('21.02.12','InputFormat', 'yy.MM.dd')
yields the desired output
datetime
12-Feb-2021
However, explicitly stating a four-digit year
datetime('21.02.12','InputFormat', 'yyyy.MM.dd')
does not produce an error, but rather the output
datetime
12-Feb-0021
Rather than shifting to the first century, I want to get an error message, hinting at the invalid date format. How can I realize this?
0 Comments
Accepted Answer
Cris LaPierre
on 12 Feb 2021
Edited: Cris LaPierre
on 12 Feb 2021
Unfortunately, 0021 is a valid date. Rather than rely on datetime to do this, you will likely need to create your own error message.
d=datetime('21.02.12','InputFormat', 'yyyy.MM.dd')
if year(d)<2000
error("Date format is incorrect")
end
5 Comments
Stephen23
on 12 Feb 2021
Edited: Stephen23
on 12 Feb 2021
The datetime documentation states "yyy, yyyy ... Year, using at least the number of digits specified by the number of instances of'y'"
From that description I would not get the meaning that 'yyyy' will also match years with fewer digits, as it does in fact clearly state that it uses "at least the number of digits specified".
"The same thing happens with month and day."
Although the descriptions in the documentation do not state "at least the number of digits", e.g.:
"MM Month, numerical using two digits"
It seems the there are subtle diffferences between how the format string is interpreted when used to import dates vs. how it is interpreted (and described in the documentation) when used to format dates. It might be flexible when interpreting, but this is not clear from the docs (and as this thread shows).
Does this mean that there is no practical difference between M and MM for interpreting?
More Answers (0)
See Also
Categories
Find more on Time Series Objects in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!