如何获得经过时间&格式化吗?

时间:2010-12-23 02:57:25

标签: delphi

我有两个unix时间戳作为LONG INT。我想从结尾开始减去经过的时间并将其格式化为hh:mm:ss

我该怎么做?感谢

3 个答案:

答案 0 :(得分:8)

您可以使用UnixToDateTimeFormatDateTime函数查看此示例

uses
  DateUtils,
  SysUtils;

var
  StartUnixTime : Int64;
  EndUnixTime   : Int64;

  StartDateTime : TDateTime;
  EndDateTime   : TDateTime;
begin
  try
    StartUnixTime:=1293062827;
    EndUnixTime  :=1293070000;

    //option 1 converting both unix times to TDatetime and then subtract
    StartDateTime:=UnixToDateTime(StartUnixTime);
    EndDateTime  :=UnixToDateTime(EndUnixTime);    
    Writeln(Format('Elapsed time %s',[FormatDateTime('hh:nn:ss',EndDateTime-StartDateTime)]));

    //option 2 subtract directly and then convert to TDatetime
    Writeln(Format('Elapsed time %s',[FormatDateTime('hh:nn:ss',UnixToDateTime(EndUnixTime-StartUnixTime))]));

  except
    on E:Exception do
      Writeln(E.Classname, ': ', E.Message);
  end;
  Readln;
end.

此外,如果您想获得年,月和日,您可以通过这种方式使用YearsBetweenMonthsBetweenDaysBetween功能。

Writeln(Format('Years %d Months %d Days %d',[YearsBetween(EndDateTime,StartDateTime),MonthsBetween(EndDateTime,StartDateTime),DaysBetween(EndDateTime,StartDateTime)]));

答案 1 :(得分:1)

UnixTime1 := 123456;
UnixTime2 := 123460;

Diff := UnixTime2 - UnixTime1;
if Diff > 24 * 60 * 60 then
  raise Exception.CreateFmt('Time difference (%s seconds) is longer than a day.', [Diff]);
s := Format('%.2d:.%2d:%.2d', [Diff div 60 div 60, (Diff div 60) mod 60, Diff mod 60]);

答案 2 :(得分:1)

这个答案没有产生我想要的结果。我选择使用OvcDate.DateDiff程序来提供我正在寻找的结果。

procedure TBCSJEmpdm.q1CalcFields(DataSet: TDataSet);
var
  das, mos, yrs : Integer;
begin
  OvcDate.DateDiff(DateTimeToStDate(DataSet.FieldByName('fromd').AsDateTime),
    DateTimeToStDate(DataSet.FieldByName('tod').AsDateTime), das, mos, yrs);      
  DataSet.FieldByName('das').AsInteger := das;
  DataSet.FieldByName('mos').AsInteger := mos;
  DataSet.FieldByName('yrs').AsInteger := yrs;
end;

此方法给出两个日期之间经过的年,月和日。 OvcDate需要ovc.inc文件。如果您需要,请告诉我。