常用时间结构体和函数
1、tm直接存储年月日的是一个结构
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有关)*/
};
2、
struct timezone{
int tz_minuteswest;/*格林威治时间往西方的时差*/
int tz_dsttime;/*DST 时间的修正方式*/
}
3、
time_t 这种类型就是用来存储从1970年到现在经过了多少秒
4、
结构体timeval的定义为:
struct timeval{
long int tv_sec; 秒数
long int tv_usec; 微秒数
}
5、
通过gettimeofday()函数来获取时间
int gettimeofday(struct timeval* tv,struct timezone* tz); 返回时间差
例子
#include <stdio.h>
#include <sys/time.h>
int main(void)
{
struct timeval tx;
gettimeofday(&tx,NULL);
printf("获取的秒时间 = %ld 获取的微秒时间 =%ld\n",tx.tv_sec,tx.tv_usec);
return 0;
}
不知道为什么,编译出来是第八时区的时间,是不是执行的系统的原因
带时区方式
#include <stdio.h>
#include <sys/time.h>
int main(void)
{
struct timeval tx;
struct timezone tz;
gettimeofday(&tx,&tz);
printf("获取的秒时间 = %ld 获取的微秒时间 =%ld\n",tx.tv_sec,tx.tv_usec);
printf("与格林尼治的时差 = %ld 、DST矫正时差=%ld\n",tz.tz_minuteswest,tz.tz_dsttime);
tz.tz_minuteswest根据参数名称知道单位是分钟,我们可以转换成转换一下小时
printf("格林尼治相对于北京时间 time =%d\n",tz.tz_minuteswest/60);
return 0;
}
6、
#include <time.h>
char *asctime(const struct tm* timeptr);
将结构中的信息转换为真实世界的时间,以字符串的形式显示
7、
类似6
char *ctime(const time_t* timep);
8、
将struct tm 结构的时间转换为从1970年至今的秒数
time_t time(time_t* t);
9、
定义函数,返回当前距离1970年的秒数和微妙数,后面的tz是时区
struct tm* gmtime(const time_t* timep);
10、
和gmtime类似,但是它是经过时区转换的时间。
time_t mktime(struct tm* timeptr);
11、
使用 timer 的值来填充 tm 结构。timer 的值被分解为 tm 结构,并用本地时区表示。
struct tm* localtime(const time_t* timep);
存储时间常见的有两种存储方式,一种是从1970年到现在经过了多少秒,一种是用一个结构来分别存储年月日时分秒的。
time_t 这种类型就是用来存储从1970年到现在经过了多少秒,要想更精确一点,可以用结构struct timeval,它精确到微妙。
Settimeofday、设置系统时间
date、查看和设置系统时间