Linux time()函數


函數簡介

  函數名: time

  頭文件:time.h

  函數原型:time_t time(time_t * timer)

  功能: 獲取當前的系統時間,返回的結果是一個time_t類型,其實就是一個大整數,其值表示從CUT(Coordinated Universal Time)時間1970年1月1日00:00:00(稱為UNIX系統的Epoch時間)到當前時刻的秒數。然后調用localtime將time_t所表示的CUT時間轉換為本地時間(我們是+8區,比CUT多8個小時)並轉成struct tm類型,該類型的各數據成員分別表示年月日時分秒。

  補充說明:time函數的原型也可以理解為 long time(long *tloc),即返回一個long型整數。因為在time.h這個頭文件中time_t實際上就是:

  #ifndef _TIME_T_DEFINED

  typedef long time_t; /* time value */

  #define _TIME_T_DEFINED /* avoid multiple defines of time_t */

  #endif

  即long。

 

  函數應用舉例

  程序例1:

  time函數獲得日歷時間。日歷時間,是用“從一個標准時間點到此時的時間經過的秒數”來表示的時間。這個標准時間點對不同的編譯器來說會有所不同,但對一個編譯系統來說,這個標准時間點是不變的,該編譯系統中的時間對應的日歷時間都通過該標准時間點來衡量,所以可以說日歷時間是“相對時間”,但是無論你在哪一個時區,在同一時刻對同一個標准時間點來說,日歷時間都是一樣的。

  #include <time.h>

  #include <stdio.h>

    int main(void)

  {

  time_t t; t = time(NULL);

  printf("The number of seconds since January 1, 1970 is %ld",t);

  return 0;

  }

 

  程序例2:

  //time函數也常用於隨機數的生成,用日歷時間作為種子。

  #include <stdio.h>

  #include <time.h>

  #include<stdlib.h>

  int main(void)

  {

  int i;

  srand((unsigned) time(NULL));

  printf("ten random numbers from 0 to 99\n\n");

  for(i=0;i<10;i++)

  {

  printf("%d\n",rand()%100);

  }

  return 0;
 
    }
 

  程序例3:

  用time()函數結合其他函數(如:localtimegmtimeasctimectime)可以獲得當前系統時間或是標准時間。

  #include <stdio.h>

  #include <stddef.h>

  #include <time.h>

  int main(void)

  {

  time_t timer;//time_t就是long int 類型

  struct tm *tblock;

  timer = time(NULL);//這一句也可以改成time(&timer);

  tblock = localtime(&timer);

  printf("Local time is: %s\n",asctime(tblock));

  return 0;

  }

注:一下為linux  man手冊中關於time相關函數的手冊

CTIME(3)                   Linux Programmer's Manual                  CTIME(3)

NAME
       asctime,   ctime,   gmtime,   localtime,  mktime,  asctime_r,  ctime_r,
       gmtime_r, localtime_r - transform date and time to broken-down time  or
       ASCII

SYNOPSIS
       #include <time.h>

       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);

   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

       asctime_r(), ctime_r(), gmtime_r(), localtime_r():
       _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _BSD_SOURCE || _SVID_SOURCE ||
       _POSIX_SOURCE

 

 


免責聲明!

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



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