天天看點

Linux下的時間函數:設定及擷取時間

一、時間函數

       time_t time(time_t *t);

       char *asctime(const struct tm *tm);

       char *asctime_r(const struct tm *tm, char *buf);

       char *ctime(const time_t *timep);

       char *ctime_r(const time_t *timep, char *buf);

       struct tm *gmtime(const time_t *timep); //擷取的為英國時間

       struct tm *gmtime_r(const time_t *timep, struct tm *result);

       struct tm *localtime(const time_t *timep);      //擷取的為本地時間,注意與英國時間的差別。

       struct tm *localtime_r(const time_t *timep, struct tm *result);

       time_t mktime(struct tm *tm);

       double difftime(time_t time1, time_t time0);

       int gettimeofday(struct timeval *tv, struct timezone *tz);

       int settimeofday(const struct timeval *tv , const struct timezone *tz);

Linux下的時間函數:設定及擷取時間

二、設定和擷取時間

#include <stdio.h>

#include <time.h>

int main(void)

{

       time_t t1;

       time_t t2;

       struct tm *my_tm;

       char buf[128] = {0};

       //自Epoch (00:00:00 UTC, January 1,1970)的秒數

       t1 = time(&t1);

       printf("%d\n", t1);                       //1355905754

       t2 = time(&t2);

       sleep(1);

       printf("%lf\n", difftime(t2, t1));  //t1,t2相差:1.000000,有時候可以用這個函數來做僞定時器

       printf("%s\n",ctime(&t1));        //Wed Dec 19 16:29:14 2012

       //init tm

       my_tm->tm_year = 2012-1900;

       my_tm->tm_mon = 12-1;

       my_tm->tm_mday = 12;

       my_tm->tm_hour = 12;

       my_tm->tm_min = 12;

       my_tm->tm_sec = 12;

      //設定時間

       t1 = mktime(my_tm);

       //擷取時間

       my_tm = localtime(&t1);

       sprintf(buf, "%04d-%02d-%02d  %02d:%02d:%02d",

                     my_tm->tm_year + 1900, my_tm->tm_mon + 1, my_tm->tm_mday, my_tm->tm_hour, my_tm->tm_min, my_tm->tm_sec);

       printf("%s\n", buf);              //2012-12-12  12:12:12

       return 0;

}

     沒那麼簡單,就這麼簡單!

Linux下的時間函數:設定及擷取時間

    幸福很簡單,簡單到時間一沖即淡,一淡就散!

Linux下的時間函數:設定及擷取時間

繼續閱讀