Linux的時間函數

 http://blog.163.com/tianle_han/blog/static/6617826200921754959958/

 

 一、時間相關說明

格林威治時間表示0時區的標準時間。其他時區的時間和此標準時間均有時間差。UTC(Universal Time Coordinated)是世界協調時間,是格林威治時間在互聯網中的表示方法

二、標準C語言時間函數

1、time(取得本地目前的時間秒數)

#include<time.h>

time_t time(time_t *t);

 

函數說明  此函數會返回從公元1970年1月1日的UTC時間從0時0分0秒算起到現在所經過的秒數。如果t 並非空指針的話,此函數也會將返回值存到t指針所指的內存。

 

返回值  成功則返回秒數,失敗則返回((time_t)-1)值,錯誤原因存於errno中。

time_t 定義爲long int

範例  #include<time.h>

mian()

{

long int seconds= time((time_t*)NULL);

printf(“%d/n”,seconds);

}

 

執行  9.73E+08

2、gmtime(根據本地時間取得目前的UTC時間)

#include<time.h>

struct tm*gmtime(const time_t*timep);

 

函數說明  gmtime()將參數timep 所指的time_t 結構中的信息轉換成真實世界所使用的時間日期表示方法,然後將結果由結構tm返回。

結構tm的定義爲

struct tm

{

int tm_sec;

int tm_min;

int tm_hour;

int tm_mday;/* day of the month */--------------就是幾號唄

int tm_mon;

int tm_year;

int tm_wday;  /* day of the week */

int tm_yday; /* day in the year */

int tm_isdst;  /* daylight saving time */

};這個就叫Broken-down  time

int tm_sec 代表目前秒數,正常範圍爲0-59,但允許至61秒

int tm_min 代表目前分數,範圍0-59

int tm_hour 從午夜算起的時數,範圍爲0-23

int tm_mday 目前月份的日數,範圍01-31

int tm_mon 代表目前月份,從一月算起,範圍從0-11

int tm_year 從1900 年算起至今的年數

int tm_wday 一星期的日數,從星期一算起,範圍爲0-6

int tm_yday 從今年1月1日算起至今的天數,範圍爲0-365

int tm_isdst 日光節約時間的旗標

此函數返回的時間日期未經時區轉換,而是UTC時間。

 

返回值  返回結構tm代表目前UTC 時間

 

範例  #include <time.h>

main(){

char *wday[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};

time_t timep;

struct tm *p;

time(&timep);

p=gmtime(&timep);

printf(“%d%d%d”,(1900+p->tm_year), (1+p->tm_mon),p->tm_mday);

printf(“%s%d;%d;%d/n”, wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec);

}

 

執行  2000/10/28 Sat 8:15:38

 

3、localtime(取得當地目前UTC時間和日期) 

#include<time.h>

struct tm *localtime(const time_t * timep);

 

函數說明  localtime()將參數timep所指的time_t結構中的信息轉換成真實世界所使用的時間日期表示方法,然後將結果由結構tm返回。結構tm的定義請參考gmtime()。此函數返回的時間日期已經轉換成當地時區。

 

返回值  返回結構tm代表目前的當地時間。

 

範例  #include<time.h>

main(){

char *wday[]={“Sun”,”Mon”,”Tue”,”Wed”,”Thu”,”Fri”,”Sat”};

time_t timep;

struct tm *p;

time(&timep);

p=localtime(&timep); /*取得當地時間*/

printf (“%d%d%d ”, (1900+p->tm_year),( l+p->tm_mon), p->tm_mday);

printf(“%s%d:%d:%d/n”, wday[p->tm_wday],p->tm_hour, p->tm_min, p->tm_sec);

}

 

執行  2000/10/28 Sat 11:12:22

4、ctime(將時間和日期以字符串格式表示) 

#include<time.h>

char *ctime(const time_t *timep);

 

函數說明  ctime()將參數timep所指的time_t結構中的信息轉換成真實世界所使用的時間日期表示方法,然後將結果以字符串形態返回。此函數已經由時區 轉換成當地時間,字符串格式爲“Wed Jun 30 21 :49 :08 1993/n”。若再調用相關的時間日期函數,此字符串可能會被破壞。

 

返回值  返回一字符串表示目前當地的時間日期。

 

範例  #include<time.h>

main()

{

time_t timep;

time (&timep);

printf(“%s”,ctime(&timep));

}

 

執行  Sat Oct 28 10 : 12 : 05 2000

 

5、asctime(將時間和日期以字符串格式表示) 

#include<time.h>

char * asctime(const struct tm * timeptr);

 

函數說明  asctime()將參數timeptr所指的tm結構中的信息轉換成真實世界所使用的時間日期表示方法,然後將結果以字符串形態返回。此函數已經由時區轉換成當地時間,字符串格式爲:“Wed Jun 30 21:49:08 1993/n”

 

返回值  若再調用相關的時間日期函數,此字符串可能會被破壞。此函數與ctime不同處在於傳入的參數是不同的結構。

 

附加說明  返回一字符串表示目前當地的時間日期。

 

範例  #include <time.h>

main()

{

time_t timep;

time (&timep);

printf(“%s”,asctime(gmtime(&timep)));

}

執行  Sat Oct 28 02:10:06 2000

 

6、mktime(將時間結構數據轉換成經過的秒數) 

#include<time.h>

time_t mktime(strcut tm * timeptr);

 

函數說明  mktime()用來將參數timeptr所指的tm結構數據轉換成從公元1970年1月1日0時0分0 秒算起至今的UTC時間所經過的秒數。

 

返回值  返回經過的秒數。

 

範例  /* 用time()取得時間(秒數),利用localtime()

轉換成struct tm 再利用mktine()將struct tm轉換成原來的秒數*/

#include<time.h>

main()

{

time_t timep;

strcut tm *p;

time(&timep);

printf(“time() : %d /n”,timep);

p=localtime(&timep);

timep = mktime(p);

printf(“time()->localtime()->mktime():%d/n”,timep);

}

 

執行  time():974943297

time()->localtime()->mktime():974943297

 

三、linux系統時間函數

1、gettimeofday(取得目前的時間) 

#include <sys/time.h>

#include <unistd.h>

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

 

函數說明  gettimeofday()會把目前的時間有tv所指的結構返回,當地時區的信息則放到tz所指的結構中。

timeval結構定義爲:

struct timeval{

long tv_sec; /*秒*/

long tv_usec; /*微秒*/

};

timezone 結構定義爲:

struct timezone{

int tz_minuteswest; /*和Greenwich 時間差了多少分鐘*/

int tz_dsttime; /*日光節約時間的狀態*/

};

上述兩個結構都定義在/usr/include/sys/time.h。tz_dsttime 所代表的狀態如下

DST_NONE /*不使用*/

DST_USA /*美國*/

DST_AUST /*澳洲*/

DST_WET /*西歐*/

DST_MET /*中歐*/

DST_EET /*東歐*/

DST_CAN /*加拿大*/

DST_GB /*大不列顛*/

DST_RUM /*羅馬尼亞*/

DST_TUR /*土耳其*/

DST_AUSTALT /*澳洲(1986年以後)*/

 

返回值  成功則返回0,失敗返回-1,錯誤代碼存於errno。附加說明EFAULT指針tv和tz所指的內存空間超出存取權限。

 

範例  #include<sys/time.h>

#include<unistd.h>

main(){

struct timeval tv;

struct timezone tz;

gettimeofday (&tv , &tz);

printf(“tv_sec; %d/n”, tv,.tv_sec) ;

printf(“tv_usec; %d/n”,tv.tv_usec);

printf(“tz_minuteswest; %d/n”, tz.tz_minuteswest);

printf(“tz_dsttime, %d/n”,tz.tz_dsttime);

}

 

執行  tv_sec: 974857339

tv_usec:136996

tz_minuteswest:-540

tz_dsttime:0

 

2、settimeofday(設置目前時間)

#include<sys/time.h>

#include<unistd.h>

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

 

函數說明  settimeofday()會把目前時間設成由tv所指的結構信息,當地時區信息則設成tz所指的結構。詳細的說明請參考gettimeofday()。注意,只有root權限才能使用此函數修改時間。

 

返回值  成功則返回0,失敗返回-1,錯誤代碼存於errno。

錯誤代碼  EPERM 並非由root權限調用settimeofday(),權限不夠。

EINVAL 時區或某個數據是不正確的,無法正確設置時間。

3、clock_gettime(獲取指定時鐘的時間值)

#include <time.h>

int clock_gettime( clockid_t clock_id,struct timespec * tp );

說明:clock_id指定要獲取時間的時鐘,根據Posix的指定可以是以下值:

CLOCK_REALTIME

Systemwide realtime clock.

 

CLOCK_MONOTONIC

Represents monotonic time. Cannot be set.

 

CLOCK_PROCESS_CPUTIME_ID

High resolution per-process timer.

 

CLOCK_THREAD_CPUTIME_ID

Thread-specific timer.

 

CLOCK_REALTIME_HR

High resolution version of CLOCK_REALTIME.

 

CLOCK_MONOTONIC_HR

High resolution version of CLOCK_MONOTONIC.

 

struct timespec {

time_t tv_sec;        /* seconds */

long  tv_nsec;       /* nanoseconds 納秒*/

};

 

4、adjtimex(tune kernel clock)

#include <sys/timex.h>

int adjtimex(struct timex *buf);

說明:

Linux  uses  David L. Mills' clock adjustment algorithm (see RFC 1305).The system call adjtimex() reads and optionally sets adjustment parame-ters  for  this  algorithm.   It  takes a pointer to a timex structure,updates kernel parameters from  field  values,  and  returns  the  same structure  with  current  kernel values.  This structure is declared as follows:

struct timex {

int modes;           /* mode selector */

long offset;         /* time offset (usec) */

long freq;           /* frequency offset (scaled ppm) */

long maxerror;       /* maximum error (usec) */

long esterror;       /* estimated error (usec) */

int status;          /* clock command/status */

long constant;       /* pll time constant */

long precision;      /* clock precision (usec) (read only) */

long tolerance;      /* clock frequency tolerance (ppm) (read only) */

struct timeval time; /* current time (read only) */

long tick;           /* usecs between clock ticks */

};

The modes field determines which parameters, if any, to  set.   It  may contain a bitwise-or combination of zero or more of the following bits:

 

#define ADJ_OFFSET            0x0001 /* time offset */

#define ADJ_FREQUENCY         0x0002 /* frequency offset */

#define ADJ_MAXERROR          0x0004 /* maximum time error */

#define ADJ_ESTERROR          0x0008 /* estimated time error */

#define ADJ_STATUS            0x0010 /* clock status */

#define ADJ_TIMECONST         0x0020 /* pll time constant */

#define ADJ_TICK              0x4000 /* tick value */

#define ADJ_OFFSET_SINGLESHOT 0x8001 /* old-fashioned adjtime() */ 

Ordinary users are restricted to a zero value for mode.  Only the supe-ruser may set any parameters. 

RETURN VALUE

On success, adjtimex() returns the clock state: 

#define TIME_OK   0 /* clock synchronized */

#define TIME_INS  1 /* insert leap second */

#define TIME_DEL  2 /* delete leap second */

#define TIME_OOP  3 /* leap second in progress */

#define TIME_WAIT 4 /* leap second has occurred */

#define TIME_BAD  5 /* clock not synchronized */ 

On failure, adjtimex() returns -1 and sets errno. 

ERRORS

EFAULT

buf does not point to writable memory. 

EINVAL

An attempt is made to set buf.offset to a value outside the range -131071 to +131071, or to set buf.status to a value other than those listed above, or to set buf.tick to a value outside the range 900000/HZ to 1100000/HZ, where HZ is the system  timer interrupt frequency. 

EPERM

buf.mode is non-zero and the caller does not have sufficient privilege.Under Linux the CAP_SYS_TIME capability is required.

CONFORMING TO

adjtimex() is Linux specific and should not be used in programs intended to be portable. See adjtime(3) for a more portable, but less flexible, method of adjusting the system clock.

發佈了45 篇原創文章 · 獲贊 3 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章