How can I convert 8 digit "20171203" date to proper format?
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
ThB
am 10 Feb. 2017
Beantwortet: Peter Perkins
am 13 Feb. 2017
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?
Akzeptierte Antwort
Star Strider
am 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.
0 Kommentare
Weitere Antworten (2)
dpb
am 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...
0 Kommentare
Peter Perkins
am 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.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Dates and Time finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!