Delphi中的时间戳(%d)相当于什么?

时间:2017-09-05 17:02:27

标签: delphi timestamp delphi-7 executable

我想运行一个带有时间戳作为参数的应用程序。在C中,我使用类似的东西:

char startCommand[64];
sprintf_s(startCommand, 64, "l2.bin %d", time(NULL));
HANDLE hProcess = CreateProcess( NULL, startCommand, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi );

是否可以在此Delphi代码中添加timestamp参数?

var
  Play : string;
  Par : string;
begin
  Play := 'myfile.exe';
  Par := '??'; // the parameter - Timestamp
  ShellExecute(TForm(Owner).Handle, nil, PChar(Play), PChar(Par), nil, SW_SHOWNORMAL);
end;

我必须先DateTimeToStr吗?

2 个答案:

答案 0 :(得分:4)

C time()函数"返回自纪元(1970年1月1日00:00:00)以来的时间,以秒为单位测量"。您可以使用Delphi的DateUtils.SecondsBetween()函数来获得类似的值,例如:

uses
  ..., Windows, DateUtils;

function CTime: Int64;
var
  SystemTime: TSystemTime;
  LocalTime, UTCTime: TFileTime;
  NowUTC, EpochUTC: TDateTime;
begin
  // get Jan 1 1970 UTC as a TDateTime...
  DateTimeToSystemTime(EncodeDate(1970, 1, 1), SystemTime);
  if not SystemTimeToFileTime(SystemTime, LocalTime) then RaiseLastOSError;
  if not LocalFileTimeToFileTime(LocalTime, UTCTime) then RaiseLastOSError;
  if not FileTimeToSystemTime(UTCTime, SystemTime) then RaiseLastOSError;
  EpochUTC := SystemTimeToDateTime(SystemTime);

  // get current time in UTC as a TDateTime...
  GetSystemTime(SystemTime);
  with SystemTime do
    NowUTC := EncodeDateTime(wYear, wMonth, wDay, wHour, wMinute, wSecond, wMilliseconds);

  // now calculate the difference in seconds...
  Result := SecondsBetween(NowUTC, EpochUTC);
end;

或者,您可以使用DateUtils.DateTimeToUnix()功能:

uses
  ..., Windows, DateUtils;

function CTime: Int64;
var
  SystemTime: TSystemTime;
  NowUTC: TDateTime;
begin
  // get current time in UTC as a TDateTime...
  GetSystemTime(SystemTime);
  with SystemTime do
    NowUTC := EncodeDateTime(wYear, wMonth, wDay, wHour, wMinute, wSecond, wMilliseconds);

  // now calculate the difference from Jan 1 1970 UTC in seconds...
  Result := DateTimeToUnix(NowUTC);
end;

无论哪种方式,你都可以这样做:

var
  Play : string;
  Par : string;
begin
  Play := 'myfile.exe';
  Par := IntToStr(CTime());
  ShellExecute(TForm(Owner).Handle, nil, PChar(Play), PChar(Par), nil, SW_SHOWNORMAL);
end;

或者,使用CreateProcess()代替,类似于C代码正在做的事情:

var
  startCommand : string;
  hProcess: THandle;
  si: TStartupInfo;
  pi: TProcessInformation;
begin
  startCommand := Format('%s %d', ['myfile.exe', CTime()]);
  ...
  ZeroMemory(@si, sizeof(si));
  si.cb := sizeof(si);
  si.dwFlags := STARTF_USESHOWWINDOW;
  si.wShowWindow := SW_SHOWNORMAL;
  if CreateProcess(nil, PChar(startCommand), nil, nil, False, 0, nil, nil, si, pi) then
  begin
    hProcess := pi.hProcess;
    ...
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
  end;
  ...
end;

答案 1 :(得分:1)

time(NULL)返回自1970年1月1日UTC(Unix时间)

以来经过的时间(以秒为单位)

您可以使用DateUtils.DateTimeToUnix

将TDateTime转换为所需格式