如何判断字符串20030110是一个有效的日期呀?(50分)

  • 主题发起人 主题发起人 hotdot
  • 开始时间 开始时间
H

hotdot

Unregistered / Unconfirmed
GUEST, unregistred user!
如题,怎么判断啊?
strtodate('20030110')转换过程,系统认为这个不是日期格式。
 
判断这样的写法的字符串是否为有效的日期:
function DoCheckDate(s: String): Boolean;
begin
result := true;
if s='' then begin
result := true;
exit;
end;
if Length(s)<8 then begin
result := false;
exit;
end;
if Copy(s,1,4)<'0000' then begin
result := false;
exit;
end;
if (Copy(s,5,2)>'12') or (Copy(s,5,2)<='00') then begin
result := false;
exit;
end;
if (Copy(s,7,2)>IntToStr(MonthDays[IsLeapYear(StrToInt(Copy(s,1,4))),strToInt(Copy(s,5,2))])) then begin
result:=false;
exit;
end;
end;
 
我原来写过一个判断 200201020304(精确到分钟)是否为日期格式的函数,参考一下
function TFrmYWXXCX.TimeIsTrue(sForm,sTo: string): boolean;
function dayInMonth(sYear,sMonth: integer): integer;
begin
case sMonth of
1,3,5,7,8,10,12:result := 31;
4,6,9,11:result := 30;
2:
if ((sYear mod 4 = 0) and (sYear mod 100 <> 0)) or ((sYear mod 100 = 0) and (sYear mod 400 = 0)) then
result := 29
else
result := 28;
end;
end;
function typeIsYes(s: string): boolean;
begin
result := true;
if length(s) <> 12 then result := false;
if (strtoint(copy(s,5,2)) > 12) or (strtoint(copy(s,5,2))<1) then result := false;
if (strtoint(copy(s,7,2)) > dayInMonth(strtoint(copy(s,1,4)),strtoint(copy(s,5,2)))) or (strtoint(copy(s,7,2))<1) then result := false;
if strtoint(copy(s,9,2)) > 23 then result := false;
if strtoint(copy(s,11,2)) > 59 then result := false;
end;
begin
result := true;
TimeForm := sForm;
TimeTo := sTo;
if sForm = '' then
begin
showerr('请输入起始时间!',2);
result := false;
exit;
end;
if (sForm <> '') and (sTo = '') then
begin
if typeIsYes(sForm) = false then
begin
result := false;
showerr('时间格式出错,请参考提示的格式',2);
end
else begin
timeTo := FormatDateTime('yyyymmddhhmm',now);
sTo := timeTo;
end;
end
else
begin
if not(typeIsYes(sForm) and typeIsYes(sTo)) then
begin
result := false;
showerr('时间格式出错,请参考提示的格式',2);
end;
if sTo < sForm then
begin
result := false;
showerr('结束时间必须不能小于开始时间!',2);
end;
end;
end;
 
高手,学习ING
 
TO:jlutt-sadan
你的最后判断日期的语句中
MonthDays[IsLeapYear(StrToInt(Copy(s,1,4))),strToInt(Copy(s,5,2))]
可有 MonthDays 这个函数吗?
 
这个不是函数,在sysutils中有定义
const
MonthDays: array [Boolean] of TDayTable =
((31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31),
(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31));
 
可以利用系统的异常来判断
var
dateSTR,tmpstr:string
begin
tmpstr:='20030101';
dateSTR:=copy(tmpstr,1,4)+'-'+copy(tmpstr,2)+'-'+copy(tmpstr,6,2);
try
strtodate(dateSTR)
except
showmessage(tmpstr+'不是一个有效的日期格式!');
end;
end;
编译后运行肯定没问题!
 
多人接受答案了。
 

Similar threads

S
回复
0
查看
1K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
928
SUNSTONE的Delphi笔记
S
S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
2K
SUNSTONE的Delphi笔记
S
后退
顶部