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

조회 수: 7 (최근 30일)
Andrew
Andrew 2013년 3월 27일
댓글: David Mellinger 2022년 11월 12일
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
David Mellinger
David Mellinger 2022년 11월 12일
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.

댓글을 달려면 로그인하십시오.

답변 (1개)

Honglei Chen
Honglei Chen 2013년 3월 27일
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.

카테고리

Help CenterFile Exchange에서 Time Series Objects에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by