New Features of C ++ 11, Using std: chrono to streamline the traditional method of getting system time, stdchrono

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.