1、时间类型。
Linux下常用的时间类型有4个:time_t,struct timeval,struct timespec,struct tm。
(1)time_t是一个长整型,一般用来表示用1970年以来的秒数。
time_t long integer
(2)struct timeval有两个成员,一个是秒,一个是微妙。
struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* microseconds */
};
(3)struct timespec有两个成员,一个是秒,一个是纳秒。
struct timespec{
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
(4)struct tm是直观意义上的时间表示方法:
struct tm {
int tm_sec; /* seconds */
int tm_min; /* minutes */
int tm_hour; /* hours */
int tm_mday; /* day of the month */
int tm_mon; /* month */
int tm_year; /* year */
int tm_wday; /* day of the week */
int tm_yday; /* day in the year */
int tm_isdst; /* daylight saving time */
};
2、 时间操作
(1) 时间格式间的转换函数
主要是 time_t、struct tm、时间的字符串格式之间的转换。看下面的函数参数类型以及返回值类型:
char *asctime(const struct tm *tm);
char *ctime(const time_t *timep);
struct tm *gmtime(const time_t *timep);
struct tm *localtime(const time_t *timep);
time_t mktime(struct tm *tm);
gmtime和localtime的参数以及返回值类型相同,区别是前者返回的格林威治标准时间,后者是当地时间。
(2) 获取时间函数
两个函数,获取的时间类型看原型就知道了:
time_t time(time_t *t);
int gettimeofday(struct timeval *tv, struct timezone *tz);
3、 实例:
(1) 实例1:
struct timeval now;
struct tm tm_cur;
gettimeofday(&now, 0);
localtime_r(&now.tv_sec, &tm_cur);
(2) 实例2:
time_t now;
time(&now);
(3) 实例3:
time_t now = time(NULL);
srand(time(NULL));