1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
| #include <locale.h>
#include <time.h>
#include <sys/time.h>
#include "tlpi_hdr.h"
#define SECONDS_IN_TROPICAL_YEAR (365.24219 * 24 * 60 * 60)
int
main(int argc, char *argv[])
{
time_t t;
struct tm *gmp, *locp;
struct tm gm, loc;
struct timeval tv;
/* Retrieve time, convert and display it in various forms */
/*
time()函数返回一个time_t类型的值,是一个有符号整数,值代表当前时间离1970.1.1零点过去的秒数
*/
t = time(NULL);
printf("Seconds since the Epoch (1 Jan 1970): %ld", (long) t);
printf(" (about %6.3f years)\n", t / SECONDS_IN_TROPICAL_YEAR);
/*
timeval 结构体
struct timeval {
time_t tv_sec; // 从1970.1.1 零点开始的秒数
suseconds _t tv_usec; // 附加的毫秒 (long int)
}
*/
if (gettimeofday(&tv, NULL) == -1)
errExit("gettimeofday");
printf(" gettimeofday() returned %ld secs, %ld microsecs\n",
(long) tv.tv_sec, (long) tv.tv_usec);
/*
gmp是一个指向tm结构体的指针,
struct tm {
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday; // 一周内的第几天(星期天=0)
int tm_yday; // 一年内的第几天
int tm_isdst; // > 0 : 夏令时
= 0 : 非夏令时
< 0 : 尝试判定DTS在每年的这一时间是否生效
}
gmtime()函数能够把日历时间转换为一个对应于UTC的分解时间,也就是上面的结构体
*/
gmp = gmtime(&t);
if (gmp == NULL)
errExit("gmtime");
gm = *gmp; /* Save local copy, since *gmp may be modified
by asctime() or gmtime() */
printf("Broken down by gmtime():\n");
printf(" year=%d mon=%d mday=%d hour=%d min=%d sec=%d ", gm.tm_year,
gm.tm_mon, gm.tm_mday, gm.tm_hour, gm.tm_min, gm.tm_sec);
printf("wday=%d yday=%d isdst=%d\n", gm.tm_wday, gm.tm_yday, gm.tm_isdst);
/* The TZ environment variable will affect localtime().
Try, for example:
TZ=Pacific/Auckland calendar_time
*/
/* localtime()函数会考虑时区和夏令时设置,其他和gmtime()一致 */
locp = localtime(&t);
if (locp == NULL)
errExit("localtime");
loc = *locp; /* Save local copy */
printf("Broken down by localtime():\n");
printf(" year=%d mon=%d mday=%d hour=%d min=%d sec=%d ",
loc.tm_year, loc.tm_mon, loc.tm_mday,
loc.tm_hour, loc.tm_min, loc.tm_sec);
printf("wday=%d yday=%d isdst=%d\n\n",
loc.tm_wday, loc.tm_yday, loc.tm_isdst);
/* asctime()函数 将分解后的时间格式化为字符串,参数为一个tm结构体 */
printf("asctime() formats the gmtime() value as: %s", asctime(&gm));
/* ctime()函数 将time_t转换为可打印格式 */
printf("ctime() formats the time() value as: %s", ctime(&t));
/* mktime()函数 将一个本地时区的分解时间解释为time_t值 */
printf("mktime() of gmtime() value: %ld secs\n", (long) mktime(&gm));
printf("mktime() of localtime() value: %ld secs\n", (long) mktime(&loc));
exit(EXIT_SUCCESS);
}
|