如上图所示,Unix下的日历时间类型主要分为以下几种:
- time_t类型,其本质上是一个长整数,表示从1970-01-01 00:00:00到目前计时时间的秒数,其值通过
time_t time(time_t *tloc)
获取。 - struct timeval 和struct timespec,结构体成员除了含有一个time_t类型用于表示秒以外,还分别有一个数用来表示微秒或纳秒,其值通过
int gettimeofday(struct timeval *tv, struct timezone *tz)
或int clock_gettime(clockid_t clk_id, struct timespec *tp)
得到。 - struct tm,结构体成员包括年月日分时秒所对应的int数值,其通常通过
struct tm *localtime(const time_t *timep)
转换后得到。 - 简单年月日字符串,可以通过
char *ctime(const time_t *timep)
和char *asctime(const struct tm *tm)
转换得到。 - 自定义格式字符串,可以通过
size_t strftime(char *s, size_t max, const char *format, const struct tm *tm)
转换得到。
简单代码示例:
struct timeval time;
gettimeofday(&time, NULL);
char buf[16];
struct tm *local = localtime(&ev->time.tv_sec);
buf[strftime(buf, sizeof(buf), "%H:%M:%S", local)] = '\0';//参数local表示本地时间
printf(ev->fp, "[%s.%d]", buf, time.tv_usec);