我想运行一个以时间戳作为参数的应用程序。在 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 代码中添加时间戳参数?
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
吗?
最佳答案
C time()
函数“返回自纪元(00:00:00 UTC,1970 年 1 月 1 日)以来的时间,以秒为单位”。您可以使用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;
关于delphi - Delphi 中的时间戳 (%d) 相当于什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46060049/