convert HH:MM:SS to seconds or minutes with delphi

北慕城南 提交于 2020-01-02 07:49:05

问题


Can someone advise me on the best way to convert a duration formated HH:MM:SS to seconds or minutes only?

ie. 00:01:49 = 109secs

I´m using this code but not work

var
i: real;
j: integer;
begin
i := frac(real(StrToTime('00:00:01')));
j := trunc(frac(real(StrToTime('01:00:00'))) / i );
memo2.lines.add(inttostr(j));

when I try the code with 00:10:00 return 599

thanks


回答1:


A very flexibel tool for handling durations is TTimeSpan found in unit System.TimeSpan. You can get the result in different units (second, minutes, hours, ...) and format that to your needs.

var
  timeSpan: TTimeSpan;
begin
  timeSpan := TTimeSpan.Parse('00:01:49');
  memo2.lines.add(Format('%1.1f min', [timeSpan.TotalMinutes]));
end;



回答2:


Using the DateUtils unit:

WriteLn(SecondOfTheDay(StrToTime('00:10:00')));
WriteLn(MinuteOfTheDay(StrToTime('00:10:00')));

Outputs:

600
10

The reason why your code is not working is that floating point values often can not be exactly represented. To avoid all implementation details about how a TDateTime represents the time, use the built in functions in SysUtils and DateUtils, see Date and Time Support.




回答3:


Use DecodeTime:

http://docwiki.embarcadero.com/Libraries/XE2/en/System.SysUtils.DecodeTime

So your code should look like this:

DecodeTime(StrToTime('00:00:01'), Hour, Min, Sec, MSec);

A function that returns the seconds should look something like this:

function GetSeconds(ATimeString: string): Integer;
var
  Hour, Min, Sec, MSec: Word;
begin
  DecodeTime(StrToTime(ATimeString), Hour, Min, Sec, MSec);
  Result := Hour * 3600 + Min * 60 + Sec;
end;


来源:https://stackoverflow.com/questions/23420818/convert-hhmmss-to-seconds-or-minutes-with-delphi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!