我有以下函数,我被引导相信应该将时间四舍五入到最接近的15分钟。
function TdmData.RoundTime(T: TTime): TTime;
var h, m, s, ms : Word;
begin
DecodeTime(T, h, m, s, ms);
m := (m div 15) * 15;
s := 0;
Result := EncodeTime(h, m, s, ms);
end;
为了测试这个功能,我在表单上放置了一个按钮和一个tedit,在单击按钮时,我这样做:
begin
Edit1.Text := RoundTime('12:08:27');
end;
我在编译时得到一个错误:'不兼容的类型TTime和string'
如果有任何帮助,那就太好了。
谢谢,
导致编译失败的错误是您将string
传递给需要TTime
作为参数的函数。
一旦这是固定的,Edit1.Text
需要一个string
类型,但你的函数返回TTime
。
使用StrToTime和TimeToStr可以从string
类型获得所需的转换。
你的函数可以这样调用:
begin
Edit1.Text := TimeToStr(RoundTime(StrToTime('12:08:27'));
end;
窃取gabr用户的答案-在Delphi中:我如何将TDateTime四舍五入到最接近的秒,分钟,五分钟等?-您可以获得一个日期四舍五入到分配给interval
参数的任意最接近的值:
function RoundToNearest(time, interval: TDateTime): TDateTime;
var
time_sec, int_sec, rounded_sec: int64;
begin
time_sec := Round(time * SecsPerDay);
int_sec := Round(interval * SecsPerDay);
rounded_sec := (time_sec div int_sec) * int_sec;
if ((rounded_sec + int_sec - time_sec) - (time_sec - rounded_sec)) > 0 then
rounded_sec := rounded_sec + time_sec + int_sec;
Result := rounded_sec / SecsPerDay;
end;
,
begin
Edit1.Text := TimeToStr(RoundToNearest(StrToTime('12:08:27'), StrToTime('0:0:15')));
end;