C++ 獲取系統時間

jopen 9年前發布 | 2K 次閱讀 C/C++

實現這個功能的方法有很多,有興趣的朋友可以去自己查找一下。

獲取系統的時間  time.cpp

#include <iostream>
#include <time.h>
#include <string>

int main()
{
    std::string s;
    char stime[256] = {0};
    time_t now_time;
    time(&now_time);
     s = ctime(&now_time);
    std::cout << s << std::endl;
    return 0;
}

通過編譯,g++ -time.cpp -o time ,運行./time,后可以獲得系統時間。

輸出為:

Wed Dec 24 13:51:07 2014

然后通過函數strftime()可以選擇自己想要輸出的格式,

如:

只是輸出時,分,秒:

#include <iostream>
#include <time.h>
#include <string>

int main()
{
    std::string s;
    char stime[256] = {0};
    time_t now_time;
    time(&now_time);
    strftime(stime,sizeof(stime),"%H:%M:%S",localtime(&now_time));
    s = stime + '\0';
    std::cout << s << std::endl;
    return 0;
}

編譯后運行,輸出:

13:54:31

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!