C++:如何获得实时时间和本地时间?

seb*_*seb 14 c++ time localtime

我正在寻找一种在C++中以HH :: MM :: SS方式节省时间的方法.我在这里看到的,他们有很多的解决方案和一个小小的研究后,我选择了timelocaltime.然而,看起来这个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;
}
Run Code Online (Sandbox Code Playgroud)

典型的输出是:

1320655946
1320655948
2011-11-7, 9:52:28
2011-11-7, 9:52:28
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,time_t时间戳是正确的,但是本地时间会让一切都变得混乱.

我的问题是:如何将时间戳类型time_t转换为人类可读的时间?

Som*_*ude 19

如果你担心在重入localtimegmtime,有localtime_rgmtime_r 它可以处理多个呼叫.

在根据自己的喜好格式化时间时,请检查功能strftime.