舍入时间最接近 15 分钟

Round TTime to nearest 15 minutes

我有以下功能,我相信应该将时间舍入到最近的 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;

编译时出现错误:'Incompatible types TTime and string'

任何帮助都将非常有用。

谢谢,

导致编译失败的错误是您将 string 传递给需要 TTime 作为参数的函数。
修复后,Edit1.Text 需要 string 类型,但您的函数 returns TTime.

使用 StrToTime and TimeToStr 您可以获得与 string 类型之间的所需转换。

你的函数可以这样调用:

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

窃取 gabr user's answer - 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;