MATLAB: Inconsistent date formats across time functions

datedatestrdatetimeMATLABtime

I'm converting dates, and noticed that the format specifiers in datetime() are inconsistent with formats in datestr(). A full specification for datetime for year-month-day hour:minutes would be 'yyyy-MM-dd HH:mm', while in datestr it is 'yyyy-mm-dd HH:MM', with month and minute indicators flipping. This difference does make converting between string and numerical formats prone to programming errors.

Best Answer

That's correct, as called out in the documentation for datetime, the documentation describing how to set the display format for those arrays, and the documentation for datenum. See the big blue Note boxes on each of the three pages.
Why did we do this? From a post on Loren's blog written when datetime was first introduced:
"If you are a frequent user of date string formats, you'll recognize that some of the format specifiers for datetime are different from those for the datestr, datenum, and datevec functions.. The new format syntax allows for more options and is now consistent with the Unicode Locale Data Markup Language (LDML) standard."
I understand your concern about accidentally making a mistake in your format string. If your format string includes a minute specifier in a location that "looks like" it should be a month specifier or vice versa, we issue a warning to try to help you avoid those types of programming errors. In release R2017b:
>> d = datetime('2017-12-06 16:10', 'InputFormat', 'yyyy-mm-dd HH:MM')
Warning: The format 'yyyy-mm-dd HH:MM' contains a field for minute (m) in what appears
to be a date portion. You might have intended to use the symbol for month (M) rather
than for minute (m). See the datetime.Format property for a complete description
of the identifiers used in format character vectors.
> In verifyFormat (line 23)
In datetime (line 608)
d =
datetime
06-Oct-2017 16:12:00
>> d = datetime('2017-12-06 16:10', 'InputFormat', 'yyyy-MM-dd HH:mm')
d =
datetime
06-Dec-2017 16:10:00
I added some extra line breaks into the warning message to avoid scrolling in the preview, but I didn't change the text of the warning. I think this warning was introduced in the release when datetime was introduced.