在一个double中将秒转换为h.m.

时间:2015-04-30 07:50:08

标签: delphi

我想将一个保持秒数的整数转换为double,其中整数部分是小时,小数部分是分钟。

有没有比这样做更好的方法? (r值)

procedure TForm1.Button3Click(Sender: TObject);
var
  SecStr : string;
  SumSeconds : integer;
  m : word;
  h : word;
  d : Word;
  r : Real;
  t : TDateTime;
  x : word;

begin
  SecStr := InputBox('Convert seconds', 'Enter seconds', '1177530');
  if TryStrToInt(SecStr, SumSeconds) then
  begin
      r := 0.0;
      x := 0;
      // SumSeconds := ASummary.Sum;

      h := SumSeconds div (MinsPerHour * SecsPerMin);
      SumSeconds := SumSeconds - (h * (MinsPerHour * SecsPerMin));

      m := SumSeconds div (SecsPerMin);

      ShowMessageFmt('%d hours and %d minutes',[h, m]);

      r := StrToFloat(format('%d%s%d',[h,formatsettings.DecimalSeparator, m]))

  end;
end;

3 个答案:

答案 0 :(得分:2)

完整小时数由下式给出:

WholeHours := TotalSeconds div SecondsPerHour;

剩余秒数为:

SecondsRemaining := TotalSeconds - WholeHours * SecondsPerHour;

或者:

SecondsRemaining := TotalSeconds mod SecondsPerHour;

分数形式的剩余秒数由下式给出:

FractionalHours := SecondsRemaining / SecondsPerHour;

所以,你的最终答案是:

WholeHours + FractionalHours

然后,或许你希望知道在删除小时后剩余的完整分钟数,正如@LURD建议的那样。那将是:

WholeMinutes := SecondsRemaining div SecondsPerMinute;

然后最终的答案是:

WholeHours + WholeMinutes / MinutesPerHour

作为另一种选择,为了计算小时,分钟和秒,代码运行如下:

SecondsRemaining := TotalSeconds;
Hours := SecondsRemaining div SecondsPerHour;
dec(SecondsRemaining, Hours * SecondsPerHour);
Minutes := SecondsRemaining div SecondsPerMinute;
dec(SecondsRemaining, Minutes * SecondsPerMinute);
Seconds := SecondsRemaining;

答案 1 :(得分:1)

添加局部变量

minutes: Integer;

然后计算

  minutes := SumSeconds div SecsPerMin;

  h := minutes div MinsPerHour;
  m := minutes mod MinsPerHour;

  r := h + m/100;

答案 2 :(得分:0)

r := DateUtils.HourSpan(0,(sumSeconds div SecsPerMin)/MinsPerDay);

var
  hours,seconds: Word;
...
Math.DivMod(sumSeconds,MinsPerHour * SecsPerMin,hours,seconds);
r := hours + (seconds div SecsPerMin)/MinsPerHour;