2011-11-07 76 views
12

我正在尋找一種方法來節省C++中的HH :: MM :: SS時間。我在這裏看到他們有很多解決方案,經過一些研究,我選擇了timelocaltime。然而,這似乎是localtime功能是有點棘手,因爲它saysC++:如何獲得實時時間和本地時間?

所有調用的localtime和gmtime的使用相同的靜態結構,所以 每次調用覆蓋以前調用的結果。

,這導致下一代碼片段顯示的問題:

#include <ctime> 
#include <iostream> 
using namespace std; 

int main() { 
time_t t1 = time(0); // get time now 
struct tm * now = localtime(& t1); 

std::cout << t1 << std::endl; 
sleep(2); 
time_t t2 = time(0); // get time now 
struct tm * now2 = localtime(& t2); 
std::cout << t2 << std::endl; 

cout << (now->tm_year + 1900) << '-' 
    << (now->tm_mon + 1) << '-' 
    << now->tm_mday << ", " 
    << now->tm_hour << ":" << now->tm_min << ":" << now->tm_sec 
    << endl; 

cout << (now2->tm_year + 1900) << '-' 
    << (now2->tm_mon + 1) << '-' 
    << now2->tm_mday << ", " 
    << now2->tm_hour << ":" << now2->tm_min << ":" << now2->tm_sec 
    << endl; 
} 

這方面的一個典型輸出是:

1320655946 
1320655948 
2011-11-7, 9:52:28 
2011-11-7, 9:52:28 

因此,大家可以看到,time_t時間戳是正確的,但當地時間攪亂了一切。

我的問題是:如何將時間戳ot類型time_t轉換爲人類可讀的時間?

回答

18

如果您在localtimegmtime擔心重入,有localtime_rgmtime_r可同時處理多個呼叫。

當談到根據自己的喜好格式化時,請檢查功能strftime

+1

+1。我甚至不知道* _r!謝謝! – Viet

3

localtime()調用將結果存儲在內部緩衝區中。

每次調用它時,都會覆蓋緩衝區。
另一種解決方案是製作緩衝區的副本。

time_t  t1 = time(0);   // get time now 
struct tm* now = localtime(& t1); // convert to local time 
struct tm copy = *now;    // make a local copy. 
//  ^^^ notice no star. 

但注意:唯一一次你應該轉換爲本地時間是當你顯示的值。在所有其他時間,你應該保持時間爲UTC(用於存儲和操作)。既然你只是轉換顯示轉換的對象,然後立即打印,然後事情不會出錯。

+0

+1爲了說明我只需要在最後進行轉換。謝謝! – seb

0

localtime有最好的被認爲是傳統的接口。例如,在多線程代碼中不能使用 。在多線程的 環境中,可以在Windows下使用Posix下的localtime_r或在Windows下使用localtime_s 。否則,所有你需要做的就是保存結果:

tm then = *localtime(&t1); 
// ... 
tm now = *localtime(&t2); 

它可能是更地道,但是,要立即格式化輸出之前只調用localtime
,如:

std::string 
timestampToString(time_t timeAndDate) 
{ 
    char results[100]; 
    if (strftime(results, sizeof(results), "%Y-%m-%d, %H:%M:%S", 
       localtime(&timeAndDate)) == 0) { 
     assert(0); 
    } 
    return results; 
} 

和然後書寫:

std::cout << formatTime(t1) << std::endl; 

(你也可以創建一個更通用的格式化函數,其中需要 作爲參數的格式。)

-1

您可以使用以下代碼運行連續時鐘。它很好地工作。

#include<iostream> 
#include <Windows.h> 
#include<ctime> 
using namespace std; 

void main() { 
    while(true) { 
    system("cls"); //to clear screen 
    time_t tim; 
    time(&tim); 
    cout << ctime(&tim); 
    Sleep(1); 
    } 
} 
+0

我認爲這不能回答這個問題。 (如何以人們可讀的格式顯示time_t) – andrel

+0

請在回答之前閱讀問題 –