Clear Filters
Clear Filters

How can I convert 8 digit "20171203" date to proper format?

2 views (last 30 days)
I am looking to convert dates of the following 8-diit input format "20171203" (3rd December 2017) into a proper date string which I can use for the x-axis of a graph. The dates are stored in a large 8784x1 matrix, with 24 date entries per day over a year. Can anyone help?

Accepted Answer

Star Strider
Star Strider on 10 Feb 2017
This works:
OriginalDate = [20171203; 20171204];
dn = datenum(num2str(OriginalDate,'%d'), 'yyyymmdd'); % Date Numbers
Check = datevec(dn) % Check Conversion (Delete)
Check =
2017 12 3 0 0 0
2017 12 4 0 0 0
You have to convert them to date numbers (the ‘dn’ assignment here) to use them with the datetick function.

More Answers (2)

dpb
dpb on 10 Feb 2017
Use the new(ish) '%D' format specifier with textscan--
>> d=20171203;
>> dt=textscan(num2str(d),'%{YYYYMMdd}D')
dt =
[1x1 datetime]
>> whos dt
Name Size Bytes Class Attributes
dt 1x1 149 cell
>> t=dt{:}
t =
20171203
>> t.Format
ans =
YYYYMMdd
>> t.Format='default'
t =
03-Dec-2017 00:00:00
>>
NB: The cast of dt the cell array containing a datetime object to t, the datetime class itself. There's not, apprently, a cell2... function such as cell2mat to make the cast nor is there a way to cause textscan to return the native data type which I think is a major disadvantage often...

Peter Perkins
Peter Perkins on 13 Feb 2017
If you have numbers, convert directly to datetime:
>> datetime(20171203,'ConvertFrom','yyyymmdd')
ans =
datetime
03-Dec-2017 00:00:00
Then create text in whatever format you want using cellstr. If you're using R2016b, you may find that the plot you're making already supports datetime directly, no need for you to convert. If you're using R2016a or earlier, the plot function supports datetime, but no others.
If you have text already, convert to datetime using
>> datetime('20171203','InputFormat','yyyyMMdd')
ans =
datetime
03-Dec-2017
and proceed as above.

Categories

Find more on Data Type Conversion 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!