MATLAB: Textscan won’t read the dates with spaces

datetimetextscan

Textscan doesn't work when date elements are separated by spaces. However the same format works when used with datetime function. Have a look at the following code:
textscan('1959 05 21','%{yyyy MM dd}D') % Doesn't work when there are spaces
datetime('now','Format','yyyy MM dd') % same format works with datetime function
textscan('1959-05-21','%{yyyy-MM-dd}D') % Works when when space is replaced with non letter character
textscan('1959 05 21','%{yyyy MM dd}D','whitespace','') % Works when whitespace is set to none
textscan('1959 05 21 567','%{yyyy MM dd}D%d','whitespace','') % Doesn't work
How can I make last line of the code to work?
Thanks
PS: Read Walter Roberson and per isakson's comments on the accepted answer

Best Answer

Hi Per,
The issue is that textscan's delimiter is space by default. Parsing happens first, then datatype conversion. In this case, you're getting
"1959 05 21" -> "1959","05","21"
and trying to convert each of these into it own datetime. This is a pretty common confusion.
The trick to parsing this correctly is to supply 'Delimiter' to textscan. Try:
textscan('1959 05 21','%{yyyy MM dd}D','Delimiter',',')
Hope this helps, Jeremy