Date Validation error in semantics
1 次查看(过去 30 天)
显示 更早的评论
I am not getting the proper result from this code. At the same time haven't been able to find my errors..
function valid=valid_date(year,month,day)
if integer(year,month,day)==2
if leap_year(year)==2
if month>0 && month<12
if month==2
if day>29 || day<1
valid=false;
return
else
valid=true;
return
end
elseif month==1||month==3||month==5||month==7||month==8||...
month==10||month==12
if day>31 || day<1
valid=false;
return
else
valid=true;
return
end
else
if day>30 || day<1
valid=false;
return
else
valid=true;
return
end
end
else
valid=false;
return
end
else
if month>0 && month<12
if month==2
if day>28 || day<1
valid=false;
return
else
valid=true;
return
end
elseif month==1||month==3||month==5||month==7||month==8||...
month==10||month==12
if day>31 || day<1
valid=false;
return
else
valid=true;
return
end
else
if day>30 || day<1
valid=false;
return
else
valid=true;
return
end
end
else
valid=false;
return
end
end
else
valid=false;
return
end
function result1=integer(year,month,day)
if ~isscalar(year) || year<1 || year~=fix(year)||...
~isscalar(month) || month<1 || year~=fix(month)...
~isscalar(day) || day<1 || year~=fix(day)
result1=1;
else
result1=2;
end
function result2=leap_year(year)
if mod(year,400)==0 || (mod(year,4)==0 && mod(year,100)~=0)
result2=1;
else
result2=2;
end
0 个评论
回答(1 个)
Ameer Hamza
2020-5-9
编辑:Ameer Hamza
2020-5-9
Why not use built-in MATLAB's function
function isValid = dateVal(year, month, date)
dt = datetime(year, month, date);
[y,m,d] = ymd(dt);
isValid = isequal([y, m, d], [year, month, date]);
end
Example:
K>> dateVal(1900, 2, 29)
ans =
logical
0
K>> dateVal(2000, 2, 29)
ans =
logical
1
2 个评论
Ameer Hamza
2020-5-9
Try to use breakpoint: https://www.mathworks.com/help/matlab/matlab_prog/set-breakpoints.html and run your code line by line. It will help in finding out which conditions are causing problems.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Manage Products 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!