1. 程式人生 > >C C++如何獲取當前系統時間

C C++如何獲取當前系統時間

C庫中與系統時間相關的函式定義在<time.h>標頭檔案中, C++定義在<ctime>標頭檔案中。 一、time(time_t*)函式 函式定義如下: time_t time (time_t* timer); 獲取系統當前日曆時間 UTC 1970-01-01 00:00:00開始的unix時間戳 引數:timer 存取結果的時間指標變數,型別為time_t,指標變數可以為null。如果timer指標非null,則time()函式返回值變數與timer指標一樣,都指向同一個記憶體地址;否則如果timer指標為null,則time()函式返回一個time_t變數時間。 返回值
,如果成功,獲取當前系統日曆時間,否則返回 -1。
二、結構體 struct tm
變數 型別 說明 範圍
tm_sec int 每分鐘的秒數 [0 - 61]
tm_min int 每小時後面的分鐘數 [0 - 59]
tm_hour int 凌晨開始的小時數 [0 - 23]
tm_mday int 從每月份開始算的天數 [1 - 31]
tm_mon int 從一月份開始的月份數 [0 - 11]
tm_year int 從1900年開始的年數  
tm_wday int 從每週天開始算的天數 [0 - 6]
tm_yday int 一年的第幾天,從零開始 [0 - 365]
tm_isdst int 夏令時  
       
這裡有幾個地方要注意: 1. tm_sec 在C89的範圍是[0-61],在C99更正為[0-60]。通常範圍是[0-59],只是某些系統會出現60秒的跳躍。 2. tm_mon 是從零開始的,所以一月份為0,十二月份為11。
三、本地時間轉換函式localtime(time_t*) 函式原型 struct tm * localtime (const time_t * timer); 將日曆時間轉換為本地時間,從1970年起始的時間戳轉換為1900年起始的時間資料結構
四、原始碼及編譯

current_time.cpp

#include <cstdio>
#include <ctime>

int main(int argc, char* argv[]) {
    time_t rawtime;
    struct tm *ptminfo;

    time(&rawtime);
    ptminfo = localtime(&rawtime);
    printf("current: %02d-%02d-%02d %02d:%02d:%02d\n",
            ptminfo->tm_year + 1900, ptminfo->tm_mon + 1, ptminfo->tm_mday,
            ptminfo->tm_hour, ptminfo->tm_min, ptminfo->tm_sec);
    return 0;
}


編譯及執行

$ g++ current_time.cpp

$ ./a.out

current: 2017-07-26 23:32:46