Converting dates into numbers

1 次查看(过去 30 天)
I have a int32 matrix of dates in the format YYYYMMDD and a cell array for time in the day in the format HH:MM. How can I combine both and turn it into a number I can use for plotting?

采纳的回答

Azzi Abdelmalek
Azzi Abdelmalek 2013-9-10
x=int32([19921212,19921213,19921214])'
y={'12:12', '13:13','14:14'}'
a=[num2str(x) char(y)]
b=datenum(a,'yyyymmddHH:MM')
datestr(b)
  3 个评论
Silver
Silver 2018-9-11
@Azzi and when I have the date format already sticked together like this: 2016.03.01 14:38:00 in a cell array how can I convert them to numeric so I can ue them in plot ? thks in advance
Stephen23
Stephen23 2018-9-11
@Silver: read the datenum documentation.

请先登录,再进行评论。

更多回答(1 个)

Peter Perkins
Peter Perkins 2018-9-12
Unless you're using a fairly old version of MATLAB, consider using datetimes instead of datenums. You will be happier.
>> x = int32([19921212,19921213,19921214])';
>> y = {'12:12', '13:13','14:14'}';
>> d = datetime(x,'ConvertFrom','yyyymmdd')
d =
3×1 datetime array
12-Dec-1992 00:00:00
13-Dec-1992 00:00:00
14-Dec-1992 00:00:00
>> t = duration(y,'InputFormat','hh:mm')
t =
3×1 duration array
12:12:00
13:13:00
14:14:00
>> dt = d + t
dt =
3×1 datetime array
12-Dec-1992 12:12:00
13-Dec-1992 13:13:00
14-Dec-1992 14:14:00
Then just plot whatever vs. dt. You don't need to convert the datetimes to numeric.
Actually, creating the duration directly form text requires R2018a, prior to that do this:
>> t = timeofday(datetime(y,'InputFormat','HH:mm'))
t =
3×1 duration array
12:12:00
13:13:00
14:14:00
or use text2duration on the File Exchange.

类别

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