datetime array to cell array in matlab

You can use the cellstr() function in MATLAB to convert a datetime array to a cell array of strings.

Here's an example code snippet that demonstrates this:

main.m
% Create a datetime array
dt = datetime(2022,1,1,10,0,0) + hours(0:2);

% Convert datetime array to cell array of strings
c = cellstr(dt);

% Display the cell array of strings
disp(c)
184 chars
9 lines

Output:

main.m
3x1 cell array
    {'01-Jan-2022 10:00:00'}
    {'01-Jan-2022 11:00:00'}
    {'01-Jan-2022 12:00:00'}
102 chars
5 lines

You can modify the date format using the datestr() function, as shown in the example below:

main.m
% Convert datetime array to cell array of custom-formatted strings
c2 = cellstr(datestr(dt, 'yyyy-mm-dd HH:MM:SS'));

% Display the cell array of custom-formatted strings
disp(c2)
180 chars
6 lines

Output:

main.m
3x1 cell array
    {'2022-01-01 10:00:00'}
    {'2022-01-01 11:00:00'}
    {'2022-01-01 12:00:00'}
99 chars
5 lines

Note that the size of the resulting cell array will be the same as the size of the original datetime array.

related categories

gistlibby LogSnag