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

2 次查看(过去 30 天)
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?

采纳的回答

Star Strider
Star Strider 2017-2-10
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.

更多回答(2 个)

dpb
dpb 2017-2-10
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 2017-2-13
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.

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by