I wrote this code to check for date validation, but I am stuck on how to check for 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
How do I incorporate leap year calculation?
Thanks to @gregswiss for pointing out my error in leap year calculation. This directly incorporates the check into the code, thus you do not have to include an a priori list of leap years:
if (mod(year,4) == 0 && mod(year,100) ~= 0) || mod(year,400) == 0
disp('Leap year');
else
disp('Non-leap year');
end
Just include this in your if
statement the same way you check your months. Then if your year has a corresponding entry in LeapYear
it is a leap year:
if sum(year==LeapYear)
disp('This is a leap year')
end
The reason for the sum is that year==LeapYear
will be a logical array containing 30 values, of which 29 zero and 1 one if your year
is indeed a leap year, or it will contain 30 zeros.
I recently found out about a more obscure function: eomday
which tells you the last day of the month, so a simple eomday(year,month)==29
is sufficient to tell you whether it is a leap year. (There's [leapyear
][2] as well, but that's in the aerospace toolbox)
date = input('Please enter a date in the DD/MM/YYYY format ','s')
display('hello')
tmp=strsplit(date,'/');
a(1) = str2num(tmp{1}); % Create an array out of your string
a(2) = str2num(tmp{2});
a(3) = str2num(tmp{3});
day = a(1);
display(day);
month = a(2);
display(month);
year = a(3);
display(year);
if eomday(year,month)==29
disp('Leap year');
else
disp('Non-leap year');
end
%if (mod(year,4) == 0 & mod(year,100) ~= 0) | mod(year,400) == 0
% disp('Leap year');
%else
% disp('Non-leap year');
%end
if (month==1||month==3||month==5||month==7||month==8||month==10||month==12)
if (day>=1&&day<=31)
display(' It is a valid date')
else
display(' It is NOT a valid date')
end
end