C/C++讀取時間的方法


【摘要】本文介紹C/C++下獲取日歷時間的方法,區別於JAVA語言的方便,C/C++標准庫好像並沒有一次性得到具有可讀性的HH:MM:SS的方法,本文介紹常用的三步法得出具有可讀性的時間,並且介紹了納秒和微秒的時間獲取。

1、對於C語言,需包含的頭文件:

1 #include <sys/time.h>

2、獲取日期需要先獲取日歷時間,即1970年1月1日 00:00:00至今的秒數,在linux系統為time_t類型,其相當於1個long型。

然后將time_t轉成tm結構體,tm結構體包括分、秒、時、天、月、年等數據。

使用clock_gettime獲取日歷時間代碼如下:

#include <iostream>
#include <sys/time.h>
using namespace std;
int main(){
    struct timespec tsp;
    clock_gettime(CLOCK_REALTIME,&tsp);

    struct tm *tmv = gmtime(&tsp.tv_sec);

    cout<<"日歷時間:"<<tsp.tv_sec<<endl;
    cout<<"UTC中的秒:"<<tmv->tm_sec<<endl;
    cout<<"UTC中的時:"<<tmv->tm_hour<<endl;
}

結果:
日歷時間:1475654852
UTC中的秒:32
UTC中的時:8

獲取日歷時間有如下三種:

time_t time(time_t *calptr);//精確到秒
int clock_gettime(clockid_t clock_id, struct timespec *tsp);//精確到納秒
int gettimeofday(struct timeval *restrict tp, void *restrict tzp);//精確到微秒

3、如需獲取毫秒和微秒,則不能使用以上的time_t和tm數據,在C/C++中提供了timespec和timeval兩個結構供選擇,其中timespec包括了time_t類型和納秒,timeval包括了time_t類型和微秒類型。

#include <iostream>
#include <sys/time.h>
using namespace std;
int main(){
    struct timespec tsp;
    struct timeval tvl;
    clock_gettime(CLOCK_REALTIME,&tsp);
    cout<<"timespec中的time_t類型(精度秒):"<<tsp.tv_sec<<endl;
    cout<<"timespec中的納秒類型:"<<tsp.tv_nsec<<endl;

    gettimeofday(&tvl,NULL);
    cout<<"timeval中的time_t類型(精度秒)"<<tvl.tv_sec<<endl;
    cout<<"timeval中的微秒類型:"<<tvl.tv_usec<<endl;
}

結果:
timespec中的time_t類型(精度秒):1475654893
timespec中的納秒類型:644958756
timeval中的time_t類型(精度秒)1475654893
timeval中的微秒類型:645036

4、用易於閱讀的方式顯示當前日期,C/C++提供strptime函數將time_t轉成各類型的時間格式,但是它比較復雜,以下是一個例子:

#include <iostream>
#include <sys/time.h>
using namespace std;
int main(){
    struct timespec tsp;
    clock_gettime(CLOCK_REALTIME,&tsp);
    char buf[64];
    struct tm *tmp = localtime(&tsp.tv_sec);
    if (strftime(buf,64,"date and time:%Y-%m-%d %H:%M:%S",tmp)==0){
        cout<<"buffer length is too small\n";
    }
    else{
        cout<<buf<<endl;
    }
}
結果:
date and time:2016-10-05 16:02:45

 5、C/C++中時間數據類型和時間函數的關系

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM