2017-09-05 118 views
3

我想运行时间戳作为参数的应用程序。在C中,我使用类似的东西:Delphi中时间戳(%d)的等价物是什么?

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吗?

回答

1

time(NULL)回报,因为01/01/1970 UTC(Unix时间)

可以TDateTime类型转换成需要的格式使用DateUtils.DateTimeToUnix

4

的C time()功能“在几秒钟内经过时间返回的时间,因为时代( UTC,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; 
+0

优秀的解决方案,它的工作原理,非常感谢! –

相关问题