坚持检查闰年和有效日期

时间:2015-09-13 19:21:52

标签: matlab validation date leap-year

我编写了这段代码来检查日期验证,但我仍然坚持如何检查闰年。

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 

如何纳入闰年计算?

1 个答案:

答案 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