C++11新特性,利用std::chrono精简传统获取系统时间的方法
来源:互联网 发布:货运数据 量化投资 编辑:程序博客网 时间:2024/06/03 12:30
一、传统的获取系统时间的方法
传统的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里面的新特性,使得二者合并呢?答案是肯定的。
很简单的,代码如下:
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);}
又短又简单有木有。
本文原创,如需转载,请说明出处:
http://blog.csdn.net/q229827701/article/details/41015483
2 0
- C++11新特性,利用std::chrono精简传统获取系统时间的方法
- C++11新特性,利用std::chrono精简传统获取系统时间的方法
- C++11新特性,利用auto和std::chrono获取系统时间的方法
- C++11 新的计时方法——std::chrono 大法好
- C++11 新的计时方法——std::chrono 大法好
- C++11 新的计时方法——std::chrono 大法好
- std::chrono时间处理类
- linux c 获取系统时间的方法
- C语言获取系统时间的方法
- C++11的时间库 chrono
- 【C/C++】C++11新特性:std::bind
- [C/C++11]_[初级]_[实用时间库chrono]
- C++11 std::chrono库详解
- C++11 std::chrono库详解
- C++11 std::chrono库详解
- c++11 Chrono时间库
- C获取系统时间的方法(linux下)
- C语言中获取系统时间的方法
- GDB调试
- 单例模式的C++实现
- u-boot-2014.10移植第17天----添加DM9000网卡支持(一)
- android.widget.FrameLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
- 百度移动研发2015校招笔试题
- C++11新特性,利用std::chrono精简传统获取系统时间的方法
- servlet压缩数据
- 插入排序(直接插入排序法)原理及代码
- 2005第几天
- 第十一周项目6-回文素数2
- 2006 求奇数的乘积
- 爱情那么短,遗忘那么长
- uva--185+dfs
- 数组1