1.核心理论-时间类型
Coordinated Universal Time(UTC):世界标 准时间,也就是大家所熟知的格林威治标准时间 (Greenwich Mean Time,GMT)。
Calendar Time:日历时间,是用“从一个标准 时间点(如:1970年1月1日0点)到此时经过的 秒数”来表示的时间。
第一个关键概念就是日历时间,它是指以某个标准时间点为基点到现在时刻的秒数,一般以1970.1.1零点为起点,这是最最基础的计量方式,有了这个基础数据,其它标准时间,本地时间便可轻松转化出来了.这个日历时间可通过系统调用time()来获取到。
第二个关键概念是世界标准时间,即格林威治标准时间,它可以通过系统调用gmtime()方法来由日历时间转换而来。
第三个关键概念是本地时间,即按当前所处时区来表示的本地时间,它也可以通过系统调用localtime()方法来由日历时间转换而来。
2.函数学习-时间操作
获取日历时间
函数名 :time
函数原形:
time_t time(time_t *t);
函数功能:
(返回日历时间) 获得从 1970 年 1 月 1 日 0 点到当前的秒数,存储在time_t结构之中。
所属头文件:
<time.h>
文件参数
成功:返回日历时间 失败:返回-1
参数说明:
t: 不为空的情况下 保存返回值
获取格林威治时间
函数名 : gmtime
函数原形:
struct tm *gmtime(const time_t *timep);
函数功能:
将参数timep 所指定的日历时间转化为世界标准时间
所属头文件:
<time.h>
返回值:
成功: 返回世界标准时间 ,以struct tm形式存储 struct tm { int tm_sec; /* Seconds (0-60) */ int tm_min; /* Minutes (0-59) */ int tm_hour; /* Hours (0-23) */ int tm_mday; /* Day of the month (1-31) */ int tm_mon; /* Month (0-11) */ int tm_year; /* Year - 1900 */ int tm_wday; /* Day of the week (0-6, Sunday = 0) */ int tm_yday; /* Day in the year (0-365, 1 Jan = 0) */ int tm_isdst; /* Daylight saving time */ };
参数说明:
timep: 待转化日历时间
获取本地时间
函数名 :localtime
函数原形:
struct tm *localtime(const time_t *timep);
函数功能:
将参数timep 所指定的日历时间转化为本地时间
所属头文件:
<time.h>
返回值:
成功: 返回本地时间 ,以struct tm形式存储 失败: 返回NULL
参数说明:
timep: 待转化日历时间
字符串方式显示时间
函数名 :asctime
函数原形:
char *asctime(const struct tm *tm);
函数功能:
将struct格式的时间转化为字符串
所属头文件:
<time.h>
返回值:
字符串方式显示的时间
参数说明:
待转化的tm的格式的时间
获取高精度时间
函数名 :gettimeofday
函数原形:
int gettimeofday(struct timeval *tv, struct timezone *tz);
函数功能:
获取高精度时间
所属头文件:
<sys/time.h>
返回值:
成功: 0 失败: -1
参数说明:
struct timeval *tv 保存从1970年1月1日0:0:0 到现在经历的秒数和微秒数 struct timezone *tz 通常设置为NULL struct timeval { time_t tv_sec; /* seconds */ suseconds_t tv_usec; /* microseconds */ }; struct timezone { int tz_minuteswest; /* minutes west of Greenwich */ int tz_dsttime; /* type of DST correction */ };