I came up with 2 options:
OPTION 1
clear;
start_date = '20190131';
end_date = '20191205';
myFormat = 'yyyyMMdd';
DateStrings = {start_date; end_date};
t = datetime(DateStrings,'InputFormat',myFormat);
if(~isnat(t))
disp('Everything OK');
else
disp(['Wrong string: ' strjoin((DateStrings(isnat(t))),', ')]);
end
Now option 1 works pretty good, but if you input a wrong day number, datetime will throw an error and it does not specify which of the strings (start_date / end_date) was wrong.
OPTION 2
It may seem a bit "spaghettified", but you have to wrap both the start and end date seperatly in a try/catch statement if you really want to let the user know which one of the dates was wrong.
clear;
start_date = '20190131';
end_date = '20191205';
myFormat = 'yyyyMMdd';
try
tStart = datetime(start_date,'InputFormat',myFormat);
catch
error(['Unable to convert `' start_date '` to datetime using the format `' myFormat '`']);
end
try
tEnd = datetime(end_date,'InputFormat',myFormat);
catch
error(['Unable to convert `' end_date '` to datetime using the format `' myFormat '`']);
end
if (~isnat(tStart) && ~isnat(tEnd)) %check once more if dates are valid (yes this is necessary)
disp('Dates are valid!');
else
if(isnat(tStart))
error(['Input `' start_date '` invalid datetime format. Correct format is `' myFormat '`.']);
elseif(isnat(tEnd))
error(['Input `' end_date '` invalid datetime format. Correct format is `' myFormat '`.']);
end
end