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

2 visualizaciones (últimos 30 días)
ThB
ThB el 10 de Feb. de 2017
Respondida: Peter Perkins el 13 de Feb. de 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?
  1 comentario
Stephen23
Stephen23 el 10 de Feb. de 2017
The only "proper" date format is ISO 8601, because it is internationally unambiguous.

Iniciar sesión para comentar.

Respuesta aceptada

Star Strider
Star Strider el 10 de Feb. de 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.

Más respuestas (2)

dpb
dpb el 10 de Feb. de 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 el 13 de Feb. de 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.

Categorías

Más información sobre Dates and Time en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by