Converting between datestr and datenum - what am I doing wrong?

2 views (last 30 days)
Hi All,
Can you look at my code and tell me what I'm doing wrong? I convert a date string to a date serial and then later in my code convert it back to a string. But, the final date-string is different to the original. Probably something simple, but I just can't see what's wrong.
Thanks for the help. Andrew
% Convert to date serial number
StartDate = '16/08/2011';
StartTime = '07:47:15.681530';
DateTimeSerial = datenum([StartDate ' ' StartTime])
DateTimeSerial =
8.0683e+03
% Convert to date string
datetimestr = datestr(DateTimeSerial)
datetimestr =
01-Feb-0022 07:47:15
Why is this date string different to the original date string?
Thanks
  1 Comment
David Mellinger
David Mellinger on 12 Nov 2022
My MATLAB thinks dates are in US format, which is month/day/year. I don't know if this is locale-specific or not, but in any case you can get your desired result by handing a format string as a second argument to datenum:
d = datenum('16/08/2011 07:47:15.681530', 'dd/mm/yyyy HH:MM:SS.FFF');
datestr(d)
ans =
'16-Aug-2011 07:47:15'
Note that datestr() doesn't show the milliseconds here, but they're actually present in d. You could get datestr to display them by handing it a format string as a second argument:
datestr(d, 'dd-mmm-yyyy HH:MM:SS.FFF')
ans =
'16-Aug-2011 07:47:15.681'
HOWEVER, the microseconds are not in d - that '.FFF' at the end of the format string passed to datenum means it scans only three characters after the decimal point, so the final '530' in the time string is ignored. (And using '.FFFFFF' doesn't work either; as far as I can tell, there's no way to get datenum to read in microseconds.) If you need the microseconds, scan your string using sscanf to get six numbers (y,m,d,H,M, and S) and then hand them to datenum. You might possibly run into precision issues for microseconds though.

Sign in to comment.

Answers (1)

Honglei Chen
Honglei Chen on 27 Mar 2013
To use datenum using the string form, it has to satisfy certain format. Yours is not one of them. If you change your start date to
StartDate = '16-Aug-2011'
then it will work. You can find details in the documentation of datenum and datestr.

Categories

Find more on Dates and Time 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!