一:相关结构体
struct timeval{
long tv_sec; /*秒*/
long tv_usec;/*微妙*/
};
struct timezone{
int tz_minuteswest;/*和greenwich 时间差了多少分钟*/
int tz_dsttime; /*type of DST correction*/
};
struct tm {
int tm_sec; /* 秒–取值区间为[0,59] */
int tm_min; /* 分 - 取值区间为[0,59] */
int tm_hour; /* 时 - 取值区间为[0,23] */
int tm_mday; /* 一个月中的日期 - 取值区间为[1,31] */
int tm_mon; /* 月份(从一月开始,0代表一月)取值区间为[0,11] */
int tm_year; /* 年份,其值从1900开始 */
int tm_wday; /* 星期–取值区间为[0,6],其中0代表星期天,1代表星期一,以此类推 */
int tm_yday; /* 从每年的1月1日开始的天数–取值区间为[0,365],其中0代表1月1日,1代表1月2日,以此类推 */
int tm_isdst; /* 夏令时标识符,实行夏令时的时候,tm_isdst为正。不实行夏令时的进候,tm_isdst为0;不了解情况时,tm_isdst()为负。*/
long int tm_gmtoff; /*指定了日期变更线东面时区中UTC东部时区正秒数或UTC西部时区的负秒数*/
const char *tm_zone; /*当前时区的名字(与环境变量TZ有关)*/
};
二:使用
#include <stdio.h>
#include <sys/time.h>
#include <windows.h>
int main() {
struct tm *tm_now1;
struct tm *tm_now2;
time_t time_now;
time_t time_later;
struct timeval tv;
struct timezone tz;
int diff;
gettimeofday(&tv, &tz);
//gettimeofday(&tv, NULL);
printf("tv.tv_sec = %ld\n", tv.tv_sec);
//机器时间,秒
time_now = time(NULL);
printf("secs:time_now = %ld\n", time_now);
//秒->struct tm结构
tm_now1 = localtime(&time_now);
tm_now2 = gmtime(&time_now);
//localtime_r(&time_now, tm_now1); Linux环境下
//localtime_s(tm_now1, &time_now); Windows环境下
/* 时间转化为字符串自动添加换行。 */
//秒->str eg:Tue Nov 07 12:57:43 2017
printf("str:time_now:%s", ctime(&time_now));
//struct tm结构->str eg:Tue Nov 07 12:57:43 2017
printf("str:tm_now1:%s",asctime(tm_now1));
printf("str:tm_now2:%s",asctime(tm_now2));
Sleep(2000);
time_later = time(NULL);
printf("secs:time_later = %ld\n", time_later);
diff = difftime(time_later, time_now);
printf("secs:diff time = %d\n", diff);
return 0;
}
Output
tv.tv_sec = 1510032851
secs:time_now = 1510032851
str:time_now:Tue Nov 07 13:34:11 2017
str:tm_now1:Tue Nov 07 05:34:11 2017
str:tm_now2:Tue Nov 07 05:34:11 2017
secs:time_later = 1510032853
secs:diff time = 2