New Features of C ++ 11, Using std: chrono to streamline the traditional method of getting system time, stdchrono
I. Traditional methods for obtaining system time
The traditional method for obtaining time in C ++ needs to be defined by platform. I believe there are also a lot of Baidu code.
I wrote it myself, as shown below.
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 "";}
II. C ++ 11 std standard library cross-platform method obviously, we noticed that the Code similarity under different platforms is very high, so can we use the new features in C ++ 11 to merge the two?
The answer is yes.
The Code is as follows:
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);}
Short and simple.
This article is original. If you need to reprint it, please describe the source:
Http://blog.csdn.net/q229827701/article/details/41015483