unix内核提供的基本时间服务是计算自国际标准时间公元1970年1月1日00::00:00以来经过的秒数。
#include <time.h> time_t time(time_t *calptr)
时间值总是作为函数值返回。如果参数不为空,则时间值也放在calptr指向的单元内。
int gettimeofday (struct timeval * restrict tp, void *restrict tzp)
改函数提供了更高的分辨率(微秒),tzp唯一和法值为NULL,该函数把时间存在struct timeval结构体中
struct timeval { time_t tv_sec: long tv_usec; }
time.h 中定义的struct tm 结构
struct tm { int tm_sec; /* Seconds.[0-60] (1 leap second) */ int tm_min; /* Minutes. [0-59] */ int tm_hour; /* Hours. [0-23] */ int tm_mday; /* Day. [1-31] */ int tm_mon; /* Month. [0-11] */ int tm_year; /* Year - 1900. */ int tm_wday; /* Day of week. [0-6] */ int tm_yday; /* Days in year.[0-365] */ int tm_isdst; /* DST. [-1/0/1]*/ #ifdef __USE_BSD long int tm_gmtoff; /* Seconds east of UTC. */ __const char *tm_zone; /* Timezone abbreviation. */ #else long int __tm_gmtoff; /* Seconds east of UTC. */ __const char *__tm_zone; /* Timezone abbreviation. */ #endif };
struct tm *gmtime (const time_t *calptr); struct tm * localtime(const time_t *calptr);
这两个函数返回值都是指向struct tm的指针,不同的是localtime讲日历时间转化成本地时间,而gmtime转化成国际标准时间,具体不同读者可以自己尝试。
time_t mktime(struct tm *tmptr);
这个函数是把tm结构的转化为time_t结构
char * asctime (const struct tm * tmptr); char * ctime (const time_t *calptr);
这两个函数是把时间转化为我们熟悉的字符串,如: Tue May 11 17:25:25 2011/n/0,一共26个字节
不同的是两个函数的参数,asctime传的是 tm结构的,ctime传的是time_t 结构的
我觉得最好用的一个函数是下面这个
size_t strftime(char * restrict buf,size_t maxsize, const chat * restrict format, const struct tm * restrict tmptr);
这个函数的功能就像sprintf函数一样,格式化一串字符串,把字符串输入到指定的buf中,format参数控制时间值得格式,这儿有一点,不同的format可以产生不同长度的字符串。
几种主要的格式
%F 2011-06-24
%T 00:00:00
%c Tue May 11 00:00:00 20111
%D 06/24/11
%% %
%Z EST (时区名)
%r 06:27:38 PM (12小时制)
例子
#include <stdio.h> #include <time.h> #include <string.h> int main (int argc,char *argv[]) { char strt[30]; time_t t; time(&t); printf("asctime(localtime(&t)) is %s",asctime(localtime(&t))); printf("asctime(gmtime(&t)) is %s",asctime(gmtime(&t))); printf("ctime(&t) is %s",ctime(&t)); bzero(strt,sizeof(strt)); strftime(strt,sizeof(strt),"%F %T",localtime(&t)); printf("%s/n",strt); return 0 ; }
结果为:
asctime(localtime(&t)) is Fri Jun 17 13:50:33 2011 asctime(gmtime(&t)) is Fri Jun 17 05:50:33 2011 ctime(&t) is Fri Jun 17 13:50:33 2011 2011-06-17 13:50:33
第一次写博客,请大家多提意见