2017-09-05 122 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

優秀的解決方案,它的工作原理,非常感謝! –

相關問題