我正在尋找一種方法來節省C++中的HH :: MM :: SS時間。我在這裏看到他們有很多解決方案,經過一些研究,我選擇了time
和localtime
。然而,這似乎是localtime
功能是有點棘手,因爲它says:C++:如何獲得實時時間和本地時間?
所有調用的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
轉換爲人類可讀的時間?
+1。我甚至不知道* _r!謝謝! – Viet