我正在寻找一种在 C++ 中以 HH::MM::SS 方式节省时间的方法。我在这里看到它们有很多解决方案,经过一番研究后,我选择了time
and localtime
。但是,该功能似乎localtime
有点棘手,因为它说:
所有对 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
转换为人类可读的时间?