圆形TTime到最近的15分钟

时间:2015-09-30 14:10:11

标签: delphi delphi-xe2

我有以下功能,我认为这应该是最近的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;

为了测试这个功能,我在表格上放了一个tbutton和一个tedit,然后点击我做的按钮:

begin
  Edit1.Text := RoundTime('12:08:27');
end;

编译时遇到错误:'不兼容的类型TTime和字符串'

任何帮助都会很棒。

谢谢,

1 个答案:

答案 0 :(得分:4)

导致编译失败的错误是您将string传递给需要TTime作为参数的函数。
解决此问题后,Edit1.Text需要string类型,但您的函数会返回TTime

使用StrToTimeTimeToStr,您可以从string类型获得所需的转化。

您的功能可以这样调用:

begin
  Edit1.Text := TimeToStr(RoundTime(StrToTime('12:08:27'));
end;

窃取gabr user的答案 - In Delphi: How do I round a TDateTime to closest second, minute, five-minute etc? - 您可以获取四舍五入到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;
相关问题