代碼
function[valid] = isValidDate(str)
[date1, year1] = strtok(str, ','); %Should give me the date and year
[month1, day1] = strtok(date1, ' '); %Should give me month and the day
%// 1. Take care of bad month strings
all_months = {'January', 'February','March', 'April', 'May','June',...
'July', 'August', 'September','October','November' 'December'} ;
if ~ismember(cellstr(month1),all_months)
valid = false;
return;
end
%// 2. Take care of negative or fraction days
day1 = day1(isstrprop(day1,'digit')); %// Take care of suffixes after day string
num_day = str2double(day1);
if round(num_day)~=num_day || num_day<1
valid = false;
return;
end
%// 3. Take care of fraction or negative years
num_year = str2double(strtok(year1,','));
if round(num_year)~=num_year || num_year<0
valid = false;
return;
end
lpyr =mod(num_year, 400) == 0 | (mod(num_year, 4) == 0 ~= mod(num_year, 100) == 0);
switch month1
case {'September','April','June','November'}
if num_day > 30
valid = false;
return;
end
case {'February'}
if (lpyr && num_day > 29) | (~lpyr && num_day > 28)
valid = false;
return;
end
case {'January', 'March', 'May', 'July', 'August', 'October', 'December'}
if num_day > 31;
valid = false;
return;
end
end
valid = true; %// We made it through!
return;
如果你希望有一個緊湊的代碼 -
function valid = isValidDate(str)
[date1, year1] = strtok(str, ','); %Should give me the date and year
[month1, day1] = strtok(date1, ' '); %Should give me month and the day
%// 1. Take care of bad month strings
all_months = {'January', 'February','March', 'April', 'May','June',...
'July', 'August', 'September','October','November' 'December'} ;
valid_month = ismember(cellstr(month1),all_months);
%// 2. Take care of negative or fraction days
day1 = day1(isstrprop(day1,'digit')); %// Take care of suffixes after day string
num_day = str2double(day1);
valid_day = round(num_day)==num_day && num_day>=1;
%// 3. Take care of fraction or negative years
num_year = str2double(strtok(year1,','));
valid_year = round(num_year)==num_year && num_year>=0;
%// 4. Take care of valid days based on leap year and days in a month limits
lpyr = mod(num_year, 400) == 0 | (mod(num_year, 4) == 0 ~= mod(num_year, 100) == 0);
valid_leapyear = true;
switch month1
case {'September','April','June','November'}
valid_leapyear = num_day<=30;
case {'February'}
valid_leapyear = ~((lpyr && num_day>29) || (~lpyr && num_day>28));
case {'January', 'March', 'May', 'July', 'August', 'October', 'December'}
valid_leapyear = num_day<=31;
end
valid = valid_year & valid_month & valid_day & valid_leapyear;
return;
日期的字符串格式是什麼? – Marcin 2014-09-29 00:27:46
「月,日年」如此'2012年1月29日' – 2014-09-29 02:24:19
您能詳細說明''一天之後沒有後綴嗎?'?任何可以解釋您的意思的例子嗎? – Divakar 2014-09-29 04:10:41