欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

用C/C++标准库快速获取系统实时时间

最编程 2024-08-08 17:58:36
...

本文中结合C++11引入的日期时间处理库std::chrono和C语言的localtime()函数实现获取当前时间。 

第一步,获取当前时间 

 system_clock::time_point now = std::chrono::system_clock::now();

第二步,将当前时间转换为time_格式

time_t tt = std::chrono::system_clock::to_time_t(now);

第三步,将time_格式的时间转换为tm *格式   

struct tm* tmNow = localtime(&tt);

第四步,将tm*格式的时间转换为可读的时间  

char date[20] = { 0 };
sprintf(date, "%d-%02d-%02d %02d:%02d:%02d",(int)tmNow->tm_year + 1900, (int)tmNow->tm_mon + 1, (int)tmNow->tm_mday,  (int)tmNow->tm_hour, (int)tmNow->tm_min, (int)tmNow->tm_sec);

最后,在C++中的话可以将char*字符串转换为std::string字符串来处理

std::string timeNow(date);

 

推荐阅读