字符串yyyy-mm-dd变换为日期格式,然后做运算
字符串yyyy-mm-dd转换为日期格式,然后做运算
我想获得现在日期与原日期之差
假如数据库中取得日期为'201201010101',格式为string;
测试过程
prcedure tform1.buttonqclick(sender:tobject);
var
tt,x:sting;
date,dateold:tdate;
const
t = '2012010100101';
begin
tt :=copy(t,1,4)+'-'+copy(t,5,2)+'-'+copy(t,7,2); //tt = '2012-01-01'
dataold := strtodate(tt); //出现错误,f8调试得到dateold ='49040';
date := strtodate(formatdatetime('yyyy-mm-dd',now()));
x := datetostr(date-dateold);
showmessage(x);
end;
end.
请问我上面错在哪里呢,求高人帮我修改
------解决方案--------------------
tt,x:string
------解决方案--------------------
tt :=copy(t,1,4)+DateSeparator+copy(t,5,2)+DateSeparator+copy(t,7,2);
date := strtodate(formatdatetime(ShortDateFormat,now()));
------解决方案--------------------
41142就是2012-08-21
40909就是2012-01-01
TDateTime就是Double
没有问题。
------解决方案--------------------
我想获得现在日期与原日期之差
假如数据库中取得日期为'201201010101',格式为string;
测试过程
prcedure tform1.buttonqclick(sender:tobject);
var
tt,x:sting;
date,dateold:tdate;
const
t = '2012010100101';
begin
tt :=copy(t,1,4)+'-'+copy(t,5,2)+'-'+copy(t,7,2); //tt = '2012-01-01'
dataold := strtodate(tt); //出现错误,f8调试得到dateold ='49040';
date := strtodate(formatdatetime('yyyy-mm-dd',now()));
x := datetostr(date-dateold);
showmessage(x);
end;
end.
请问我上面错在哪里呢,求高人帮我修改
------解决方案--------------------
tt,x:string
------解决方案--------------------
tt :=copy(t,1,4)+DateSeparator+copy(t,5,2)+DateSeparator+copy(t,7,2);
date := strtodate(formatdatetime(ShortDateFormat,now()));
------解决方案--------------------
41142就是2012-08-21
40909就是2012-01-01
TDateTime就是Double
没有问题。
------解决方案--------------------
- Delphi(Pascal) code
function setdatetime(s:ansistring;var dt:TDateTime):boolean; var d:TDate; t:TTime; tmp:ansistring; begin Result:=false; if length(s)<>12 then exit; tmp:=copy(s,1,8); Insert('-',tmp,5); Insert('-',tmp,8); try d:=strtodate(tmp); except exit; end; tmp:=copy(s,9,4); Insert(':',tmp,3); try t:=strtotime(tmp); except exit; end; dt:=d+t; Result:=true; end; procedure TForm1.Button1Click(Sender: TObject); var d:TDateTime; begin if setdatetime('201208211148',d) then showmessage(formatdatetime('yyyy-mm-dd,hh:nn',d)) else showmessage('日期时间字符串格式有误'); end;
------解决方案--------------------
使用上述函数求得日期时间后再相减,就得到时间差了
------解决方案--------------------
------解决方案--------------------
prcedure tform1.buttonqclick(sender:tobject);
var tt,x:sting;
dateold:tdate;
const
t = '2012010100101';
begin
tt :=copy(t,1,4)+'-'+copy(t,5,2)+'-'+copy(t,7,2);
dataold := strtodate(tt); //日期2012-01-01的值就是 49040;
x := date-dateold;//这里的“date”不是你原来的date,是“今天”
showmessage('两日期差了:'+inttostr(x)+'天');
end;
------解决方案--------------------
噢,变量类型未改变,勘正:
- Delphi(Pascal) code
prcedure tform1.buttonqclick(sender:tobject); var tt:sting; dateold:tdate; x:double; const t = '2012010100101'; begin tt :=copy(t,1,4)+'-'+copy(t,5,2)+'-'+copy(t,7,2); dataold := strtodate(tt); //日期2012-01-01的值就是 49040; x := date-dateold;//这里的“date”不是你原来的date,是“今天” showmessage('两日期差了:'+inttostr(x)+'天'); end;
------解决方案--------------------
要理解Date的结构。