失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > C++11新特性 利用std::chrono精简传统获取系统时间的方法

C++11新特性 利用std::chrono精简传统获取系统时间的方法

时间:2022-07-28 08:14:35

相关推荐

C++11新特性 利用std::chrono精简传统获取系统时间的方法

一、传统的获取系统时间的方法

传统的C++获取时间的方法须要分平台来定义。

相信百度代码也不少。

我自己写了下,例如以下。

const std::string getCurrentSystemTime(){if (PLATFORM_ANDROID || PLATFORM_IOS){struct timeval s_now;struct tm* p_tm;gettimeofday(&s_now,NULL);p_tm = localtime((const time_t*)&s_now.tv_sec);char date[60] = {0};sprintf(date, "%d-%02d-%02d%02d:%02d:%02d",(int)p_tm->tm_year + 1900,(int)p_tm->tm_mon + 1,(int)p_tm->tm_mday,(int)p_tm->tm_hour,(int)p_tm->tm_min,(int)p_tm->tm_sec);return std::string(date);}if (PLATFORM_W32){struct tm* p_tm;time_t timep;time(&timep);p_tm = localtime(&timep);char date[60] = {0};sprintf(date, "%d-%02d-%02d%02d:%02d:%02d",(int)p_tm->tm_year + 1900,(int)p_tm->tm_mon + 1,(int)p_tm->tm_mday,(int)p_tm->tm_hour,(int)p_tm->tm_min,(int)p_tm->tm_sec);log("%s",date);return std::string(date);}return "";}

二、C++11 std标准库跨平台方法

显然,我们注意到不同平台下的代码相似度非常高。那么能不能利用C++11里面的新特性,使得二者合并呢?

答案是肯定的。

非常easy的。代码例如以下:

const std::string getCurrentSystemTime(){auto tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());struct tm* ptm = localtime(&tt);char date[60] = {0};sprintf(date, "%d-%02d-%02d%02d:%02d:%02d",(int)ptm->tm_year + 1900,(int)ptm->tm_mon + 1,(int)ptm->tm_mday,(int)ptm->tm_hour,(int)ptm->tm_min,(int)ptm->tm_sec);return std::string(date);}

又短又简单有木有。

,如需转载,请说明出处:

/q229827701/article/details/41015483

如果觉得《C++11新特性 利用std::chrono精简传统获取系统时间的方法》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。