在C++实际项目中,有时候需要当前时间和过去时间做对比,因此找到了一种方法,经检测可用。
话不多说,直接上代码——
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| //getLocalTime.cpp
#include <stdio.h> #include <sys/time.h> #include <time.h> #include <unistd.h> #include <iostream> #include <sstream> #include <string> using namespace std;
std::string FaGetSysTime() { struct timeval tv; gettimeofday(&tv, NULL); struct tm* pTime; pTime = localtime(&tv.tv_sec);
std::string sTemp; std::ostringstream oss;
//year oss << pTime->tm_year + 1900 << "-";
//month if (pTime->tm_mon < 9) { oss << "0" << pTime->tm_mon + 1 << "-"; } else { oss << pTime->tm_mon + 1 << "-"; }
//day if (pTime->tm_mday <= 10) { oss << "0" << pTime->tm_mday - 1 << " "; } else { oss << pTime->tm_mday - 1 << " "; }
//hour if (pTime->tm_hour < 10) { oss << "0" << pTime->tm_hour << ":"; } else { oss << pTime->tm_hour << ":"; }
//minute if (pTime->tm_min < 10) { oss << "0" << pTime->tm_min << ":"; } else { oss << pTime->tm_min << ":"; }
//second if (pTime->tm_sec < 10) { oss << "0" << pTime->tm_sec << "."; } else { oss << pTime->tm_sec << "."; }
//ms oss << tv.tv_usec / 1000;
//us oss << tv.tv_usec % 1000;
sTemp += oss.str();
return sTemp; }
int main() { cout << "当前时间:" << FaGetSysTime() << endl;
return 0; }
|
编译结果输出:
1 2 3 4 5
| patten@patten-hp:~/workspace/collide$ g++ getLocalTime.cpp patten@patten-hp:~/workspace/collide$ ./a.out 当前时间:2019-09-22 10:06:02.663171 patten@patten-hp:~/workspace/collide$
|
关联文章: