How do I change datetime values?

12 次查看(过去 30 天)
Hello,
If I have a datetime that is: 1978-12-01 06:00:00
how do I change it to only show: 1978-12 ?
I have tried changing it with the format commando but it still shows 1978-12-01 06:00:00 and not 1978-12 when I use it in a plot.

采纳的回答

William Rose
William Rose 2023-9-19
dt1=datetime(1978,12,1)+(0:1/24:23/24); % each hour of the day
dt1.Format="yyyy-MM-dd HH:mm";
disp([dt1(1), dt1(end)])
1978-12-01 00:00 1978-12-01 23:00
dt1.Format="yyy-MM";
disp([dt1(1), dt1(end)])
1978-12 1978-12
OK
  2 个评论
William Rose
William Rose 2023-9-19
You also asked about plotting.
dt1=datetime(1978,(1:12),1); % each hour of the day
dt1.Format="yyyy-MM";
disp([dt1(1), dt1(2), dt1(end)])
1978-01 1978-02 1978-12
plot(dt1,rand(1,12),'-bx')
datetick('x',"yyyy-mm")
For datetick(), you use "mm" for months and "MM" for minutes, which is the opposite of the formatting convention for datetime(...,'Format',...). Wierd.
Steven Lord
Steven Lord 2023-9-19
For datetick(), you use "mm" for months and "MM" for minutes, which is the opposite of the formatting convention for datetime(...,'Format',...). Wierd.
The identifiers used by the Format property of datetime arrays come from the Unicode® Locale Data Markup Language (LDML) standard for dates and times, as linked in the documentation for the Format property on the datetime reference page. I'm fairly sure datetick, datenum, and the other functions that use the older set of identifiers predate that standard.
Rather than using datetick I'd recommend using the xtickformat function (and similarly ytickformat and/or ztickformat.)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Line Plots 的更多信息

产品


版本

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by