time_t 是一个长整型的别名,一般用来存储一个时间点(一般是1970年1月1日0时0分0秒)到现在的秒数。
包含文件:<time.h>
#ifndef __TIME_T
#define __TIME_T /* 避免重复定义 time_t */
typedef long time_t; /* 时间值time_t 为长整型的别名*/
#endif
函数原型: time_t time(time_t *timer)
参数说明: timer=NULL时得到当前日历时间(从1970-01-01 00:00:00到现在的秒数),timer=时间数值时,用于设置日历时间,time_t是一个unsigned long类型,上面有提到,所以要获取time的时间,先定义一个time_t的变量来存储time()函数获取的时间秒数。如果 timer不为空,则返回值也存储在变量 timer中。
函数功能: 得到当前日历时间或者设置日历时间
函数返回: 当前日历时间
实例
#include <stdio.h>
#include <time.h>
int main ()
{
time_t seconds;
seconds = time(NULL);
printf("自 1970-01-01 起的秒数 = %ld\n", seconds);
return(0);
}
可对time()函数获取到的时间秒数进行特定的格式化,既转化成年月日、时分秒:
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 到 11 */
int tm_year; /* 自 1900 起的年数 */
int tm_wday; /* 一周中的第几天,范围从 0 到 6 */
int tm_yday; /* 一年中的第几天,范围从 0 到 365 */
int tm_isdst; /* 夏令时 */
};
不过需要gmtime函数或者localtime函数才能进行转化
函数原型:
struct tm *gmtime(const time_t *timer)
C 库函数gmtime()使用 timer(可由time()函数获取)的值来填充 tm 结构,并用协调世界时(UTC)也被称为格林尼治标准时间(GMT)表示。
因为每个地方的时区不同,例如我们要获取北京时间,就应该使用localtime()来获取当前时区的时间。而GMT时间+8小时所得结果就是北京时间。
函数原型:
struct tm *localtime(const time_t *timer)
C 库函数 struct tm *localtime(const time_t *timer) 使用 timer 的值来填充 tm 结构。timer 的值被分解为 tm 结构,并用本地时区表示。
#include <stdio.h>
#include <time.h>
int main()
{
time_t timer;
struct tm* st = NULL;
timer = time(NULL);
st = localtime(&timer);
printf("%04d:%02d:%02d--%02d:%02d:%02d\n", st->tm_year+1900,\
st->tm_mon+1, st->tm_mday+1, st->tm_hour+1, st->tm_min+1, st->tm_sec+1);
return 0;
}
运行结果:
2022:05:03--20:51:38
因为time()函数是获取1970-01-01 00:00:00到现在的秒数,所以我们要手动加上一些值才能正确表示现在的时间值,年份+1900,而其他结构体成员都是从0开始计算的,所以+1使得它们从1开始计算。
timeval结构体在头文件为sys/time.h中,定义如下:
struct timeval
{
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
该结构体以1970-01-01 00:00:00 +0000 (UTC),也就是Unix中的Epoch作为0,之后的时间都是相对于Epoch流逝的秒和毫秒数。其中tv_sec是秒,tv_usec是微秒(microsecond ),即10-6秒,而不是毫秒(millisecond),10-3秒。
位于头文件sys/time.h中,函数声明如下:
int gettimeofday(struct timeval *tv, struct timezone *tz);
调用函数时,用于获取距离Epoch的时间。第一个参数就是上面的timeval结构体,gettimeofday将获取的时间装到tv指向的结构体里面。第二个参数也是结构体,定义如下:
struct timezone
{
int tz_minuteswest; /* minutes west of Greenwich */
int tz_dsttime; /* type of DST correction */
};
根据Linux的手册中关于函数gettimeofday的描述(man gettimeofday):
The use of the timezone structure is obsolete; the tz argument should normally be specified as NULL
这种使用方式是过时的,该处通常提供NULL作为参数。
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
int main()
{
struct timeval tv;
struct tm* st;
static double latest_time = 0;
gettimeofday(&tv, NULL);
latest_time = tv.tv_sec;
st = localtime(&tv.tv_sec);
printf("1970-01-01 00:00:00 到现在流逝的秒数:%f\n", latest_time);
printf("将秒数转换成日期:%04d:%02d:%02d--%02d:%02d:%02d\n", st->tm_year+1900,\
st->tm_mon+1, st->tm_mday+1, st->tm_hour+1, st->tm_min+1, st->tm_sec+1);
return 0;
}
运行结果:
1970-01-01 00:00:00 到现在流逝的秒数:1651547368.000000
将秒数转换成日期:2022:05:03--21:10:29