我编写了这段代码来检查日期验证,但我仍然坚持如何检查闰年。
date = '01/02/1990';
display('hello')
a=strsplit(date,'/');
day = a(1);
display(day);
%b=strsplit('/',date,'/');
month = a(2);
display(month);
%c=strsplit('/','/',date);
year = a(3);
display(year);
if (month==1||month==3||month==5||month==7||month==8||month==10||month==12)
if (day>=1&&day<=31)
display(' Its a valid date')
else
display(' Its NOT a valid date')
end
end
如何纳入闰年计算?
答案 0 :(得分:1)
使用datetime
函数可以使代码更健壮,更简单,该函数将处理解析并在日期无效时抛出错误
date = '01/02/1990';
try
d = datetime(date, 'InputFormat', 'dd/MM/yyyy');
% access day, month, year using: d.Day, d.Month and d.Year...
% ...
disp(' Its a valid date')
catch
disp(' Its NOT a valid date')
end