Search code examples
matlabdatetimedate-formatting

Multiple date formats in MATLAB


When formatting datetimes, datestrings and datenums in MATLAB there are two different ways in which minutes and months are represented, either as M and m or m and M respectively. Concretely, when you use when you use datestr it is different to when you use datetime. Here is an example,

startdate='01/05/2015 12:35:22';
startdt=datetime(startdate,'InputFormat','dd/MM/yyyy HH:mm:ss');
startstr=datestr(startdt,'dd/mm/yyyy HH:MM:SS');

See how for datestr we use lower-case m for month and for datetime we use upper-case M for month.

Why does MATLAB have different date formats that are applicable for these commands? What's the best approach in order to implement a consistent style of date formats in my code?


Solution

  • In R2014b MathWorks introduced a new suite of functionality (based around the datetime class) to handle dates and times, that is intended to be used as a much improved replacement for older functions such as datestr, datenum and datevec.

    One of the issues with the older functionality was that it did not use standard format strings to describe date and time formats. The newer functionality does it correctly, conforming to ISO 8601. It also has proper support for timezones and locales, calendar-based durations, and nanosecond precision.

    The older functions have nevertheless been kept, for backward-compatibility. It's possible that in some future version of MATLAB they may start to be phased out gradually. The usual process for that would be that for a couple of versions they would raise a (suppressible) warning, indicating that you might like to modify your code to use the newer functionality; and then a few versions later they would be removed (which would finally cause code still using them to error).

    I would suggest that if you're writing new code, you exclusively stick to using functionality based around datetime. If you're modifying existing code, try to be consistent in your choices, but gradually migrate your code to the newer functionality when appropriate.