Datetime conversion from string with non-matching format does not yield an error

2 views (last 30 days)
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?

Accepted Answer

Cris LaPierre
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')
d = datetime
12-Feb-0021
if year(d)<2000
error("Date format is incorrect")
end
Date format is incorrect
  5 Comments
Stephen23
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?
Tracy Carla Rios Reyes
Tracy Carla Rios Reyes on 12 Feb 2021
Prepending is the better word! Yes, I thought the format would be directly validated, but I can see the point of programming it the way you suggest. Changing the display format is not what I need, since the datevalue itself will still be wrong.
Since the problem only arises with the years, the workaround (year < 2000) is sufficient for me.

Sign in to comment.

More Answers (0)

Tags

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!