在平时编写Linux代码的时候,每次用到时间或者是时区都需要去查找资料,为了以后方便,把平时用的的相关内容做个整理,方便以后查询,毕竟好记性不如烂笔头。
相关结构体
-
struct timeval
/* A time value that is accurate to the nearest microsecond but also has a range of years. */ struct timeval{ //两个长整型分别存放秒和微妙 long tv_sec; /* Seconds. */ long tv_usec; /* Microseconds. */ };
这个结构是系统时间的另一种表示方式,精度高,而
time_t
是一个长整型,表示系统时间,精确到秒。 -
struct timezone
/* Structure crudely representing a timezone. This is obsolete and should never be used. */ struct timezone { int tz_minuteswest; /* Minutes west of GMT. */ int tz_dsttime; /* Nonzero if DST is ever in effect. */ };
该结构体存放的是时区信息,其中
tz_dsttime
为当前的状态 -
struct tm
/* ISO C `broken-down time' structure. */ 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]*/ long int __tm_gmtoff; /* Seconds east of UTC. */ const char *__tm_zone; /* Timezone abbreviation. */ };
该结构存放的是具体时间信息,需要注意的是
tm_year
是当前年-1900
,tm_mon
月份是0-11
所以1月是0
.星期tm_wday
是0-6,其中星期天为0
相关函数
-
时间获取函数
time()
/* Return the current time and put it in *TIMER if TIMER is not NULL. */ extern time_t time (time_t *__timer) __THROW;
参数
time_t *__timer
为系统时间类型指针,在函数成功返回时,将系统的当前时间赋值到参数指针上。并且并返回当前系统时间,如果失败则返回-1
并设置全局变量errno
-
字符串转换函数
ctime()
和asctime()
/* Return a string of the form "Day Mon dd hh:mm:ss yyyy\n" that is the representation of TP in this format. */ extern char *asctime (const