本文介绍了C ++:如何获取实际时间与时间和本地时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我正在寻找一种方法来节省时间在HH :: MM :: SS时尚在C + +。我在这里看到他们是很多解决方案,经过一番研究,我选择了时间和 localtime 。但是, localtime 函数似乎有点棘手,因为它说:这会导致的问题显示在下面的代码段中: #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 sleep(2); time_t t2 = time(0); // get time now struct tm * now2 = localtime(& t2); std :: cout<< t2 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 时间戳是正确的,但是本地时间混乱了一切。 我的问题是:如何将时间戳类型 time_t 转换成人类可读的时间?如果你担心 localtime 和 解决方案 > gmtime ,有 localtime_r 和 gmtime_r 可以处理多个呼叫。 > 当按照你的喜好格式化时间时,检查函数 strftime 。 I'm looking for a way to save the time in a HH::MM::SS fashion in C++. I saw here that they are many solutions and after a little research I opted for time and localtime. However, it seems like the localtime function is a little tricky, since it says: The problem that this causes is shown in the next snippet of code:#include <ctime>#include <iostream>using namespace std;int main() {time_t t1 = time(0); // get time nowstruct tm * now = localtime( & t1 );std::cout << t1 << std::endl;sleep(2);time_t t2 = time(0); // get time nowstruct 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;}A typical output for this is: 132065594613206559482011-11-7, 9:52:282011-11-7, 9:52:28So as you can see, the time_t timestamps are correct, but the localtime messes everything up.My question is: how do I convert a timestamp ot type time_t into a human-readable time? 解决方案 If you are worried about reentrancy in localtime and gmtime, there is localtime_r and gmtime_r which can handle multiple calls.When it comes to formatting the time to your liking, check the function strftime. 这篇关于C ++:如何获取实际时间与时间和本地时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-27 23:02