《UNIX环境高级编程》笔记24-时间和日期
由UNIX内核提供的基本时间服务是计算 自国际标准时间公元1970年1月1日00:00:00以来经过的秒数,以time_t表示。以下2个
函数返回当前时间。
- #include <time.h>
- time_t time(time_t * ptr); //成功则返回时间值,出错则返回-1.
时间总是作为函数值返回,如果参数不为空,则时间值也存放在由ptr指向的单元内。
如果要获取更高的分辨率(微秒级),可以使用gettimeofday函数。
- #include <sys/time.h>
- int gettimeofday(struct timeval *restrict tp, void *restrict tzp); //返回值总是0
struct timeval的定义如下:
- struct timeval{
- time_t tv_sec; //second
- long tv_usec; //microseconds
- }
取得了以秒计的整型的时间值后,通常要调用另一个时间函数将其转换成人们可读的时间和日期,下图说明了各种时间函数
之间的关系。(其中虚线表示的四个函数收到环境变量TZ的影响,如果定义了TZ,则这些函数将使用其值代替系统默认时区)
localtime和gmtime函数将time_t时间转换成年月日时分秒周日表示的时间,并将这些存放在一个tm结构中。
- struct tm{
- int tm_sec; //秒,0~60,秒可以超过59的理由是可以表示闰秒
- int tm_min; //分,0~59
- int tm_hour; //小时,0~23
- int tm_mday; //日,1~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; //夏时制标志,>0:夏时制生效,0:非夏时制,<0:此信息不可用
- }
- #include <time.h>
- struct tm* gmtime(const time_t *calptr); //将日历时间转换成国际标准时间
- struct tm* localtime(const time* calptr); //将日历时间转换成本地时间
两个函数都返回指向tm结构的指针。
函数mktime以本地时间的年,月,日等作为参数,将其转换成time_t值。
- #include <time.h>
- time_t mktime(struct tm* tmptr); //若成功则返回日历时间,出错则返回-1
函数asctime和ctime函数产生如下面形式的字符串:
Mon Oct 28 10:42:06 CST 2013
- #include <time.h>
- char *asctime(const struct tm* tmptr);
- char *ctime(const time_t *calptr);
两个函数返回值,指向以NULL结尾的字符串指针。
strftime函数类似于printf函数,将时间格式化输出。
- #include <time.h>
- size_t strftime(char* restrict buf, size_t maxsize, const char *restrict format, const struct tm* restrict tmptr);
如果成功则返回存入buf的字符数,否则返回0
下图是format的格式符表:
实践:
- #include <stdio.h>
- #include <sys/time.h>
- #include <time.h>
- int main(void){
- time_t t;
- time(&t);
- printf("%ld\n",t);
- struct timeval tv;
- gettimeofday(&tv, NULL);
- printf("%ld,%ld\n",tv.tv_sec,tv.tv_usec);
- printf("%s\n",asctime(gmtime(&t)));
- printf("%s\n",asctime(localtime(&t)));
- printf("%s\n",ctime(&t));
- printf("%ld\n",mktime(localtime(&t)));
- return 0;
- }
[email protected]:~/apue$ ./a.out
1374895850
1374895850,276840
Sat Jul 27 03:30:50 2013
Sat Jul 27 11:30:50 2013
Sat Jul 27 11:30:50 2013
1374895850
从结果来看,asctime和ctime会在字符串末尾自动加换行符。
如果增加了环境变量TZ,运行结果:
[email protected]:~/apue$ export TZ=GMT
[email protected]:~/apue$ ./a.out
1374895990
1374895990,366091
Sat Jul 27 03:33:10 2013
Sat Jul 27 03:33:10 2013
Sat Jul 27 03:33:10 2013
1374895990