2015-09-07 75 views
-1

我正在編寫一個程序,在用相機拍攝的圖像上添加時間戳。爲此,我使用Windows 7系統時間。我在下面的代碼中使用GetSystemTimeAsFileTime()C++獲取系統時間,以秒數爲單位

FILETIME ft; 
GetSystemTimeAsFileTime(&ft); 
long long ll_now = (LONGLONG)ft.dwLowDateTime + ((LONGLONG)(ft.dwHighDateTime) << 32LL); 

我想要做的是得到在當天(0〜86400)是毫秒級了所以它會像12345.678秒數量。這是做到這一點的正確方法嗎?如果是這樣,我如何轉換這個整數來獲得當天的秒數?我將在字符串中顯示時間,並使用fstream將時間放在文本文件中。

由於

+0

您希望您的毫秒數相對於UTC時區,相對於當地時區或相對於某些其他時間è? –

+0

這沒關係,因爲我有一個程序可以將系統時間轉換爲UTC時區中的GPS時間,所以時間戳會關閉 – oodan123

回答

0

不知Window APIC++標準庫(因爲C++ 11)可以這樣使用:

#include <ctime> 
#include <chrono> 
#include <string> 
#include <sstream> 
#include <iomanip> 

std::string stamp_secs_dot_ms() 
{ 
    using namespace std::chrono; 

    auto now = system_clock::now(); 

    // tt stores time in seconds since epoch 
    std::time_t tt = system_clock::to_time_t(now); 

    // broken time as of now 
    std::tm bt = *std::localtime(&tt); 

    // alter broken time to the beginning of today 
    bt.tm_hour = 0; 
    bt.tm_min = 0; 
    bt.tm_sec = 0; 

    // convert broken time back into std::time_t 
    tt = std::mktime(&bt); 

    // start of today in system_clock units 
    auto start_of_today = system_clock::from_time_t(tt); 

    // today's duration in system clock units 
    auto length_of_today = now - start_of_today; 

    // seconds since start of today 
    seconds secs = duration_cast<seconds>(length_of_today); // whole seconds 

    // milliseconds since start of today 
    milliseconds ms = duration_cast<milliseconds>(length_of_today); 

    // subtract the number of seconds from the number of milliseconds 
    // to get the current millisecond 
    ms -= secs; 

    // build output string 
    std::ostringstream oss; 
    oss.fill('0'); 

    oss << std::setw(5) << secs.count(); 
    oss << '.' << std::setw(3) << ms.count(); 

    return oss.str(); 
} 

int main() 
{ 
    std::cout << stamp_secs_dot_ms() << '\n'; 
} 

示例輸出:

13641.509 
+0

,謝謝, – oodan123

相關問題