MATLAB: Merge datetime cells to create specific datetime format

cellsdatetimemergemonthtextscan

Hi,
I used textscan to import an .txt file.
file = textscan(fileID,'%{yyyy}D %{MM}D %{dd}D %{HH}D %{mm}D %f %f %f %f','Delimiter',',', 'headerLines', 1)
Now I have 9 different cells. Cell 1 contains yyyy (2018), cell 2 contains MM (05) and Cell 3 DD (22).
However I want to merge YMD to one cell with the %{ddMMyy}D format. How can I do that? Output format should then be: 22052018
Thank you in Advance,
Renan

Best Answer

Hello,
so I found the solution by myself and will share it to later users having an similar issue:
The way to go is formatting the data from datetime -> string then merge it and then back to datetime again.
Useful functions are datestr and strcat
In my case this can be done by:
% create grabber_date
% loading the variables into length x 1 datetimes
year = grabber_file{1,1};
month = grabber_file{1,2};
day = grabber_file{1,3};
% convert to string
y = datestr(year, 'yy');
m = datestr(month, 'mm');
d = datestr(day, 'dd');
% merge using strcat
datestring = strcat(d, m, y);
% transform back to datetime
grabber_date = datetime(datestring,'InputFormat','ddMMyy', 'Format','ddMMyy');
The Output format can be varied by changing 'Format'.
You can also convert integers/doubles to datetime by using this tunnel. Just use num2str instead of datestr.
Best Regards,
Renan