一、时间类型
1、日历时间:
Calendar Time,从标准时间点(1970年01月01日00:00:00)到现在经过的秒数;
2、世界标准时间:
Coordinated Universal Time(UTC),又称格林威治标准时间(Greenwich Mean Time,GMT)。
二、目标函数
1、time:获取日历时间
1)函数原型
time_t time(time_t *t);
2)所属头文件
#include <time.h>
3)返回值
成功: 返回日历时间(秒数)
失败: -1
4)参数说明
t: 不为空(NULL)时保存返回值, 一般为空.
* 案例: 编程获取日历时间, 参数为空和不为空两种:
#include <stdio.h>
#include <time.h>
void main()
{
time_t time1;
time_t time2;
time1 = time(NULL);
time(&time2);
printf("time1: %d\ntime2: %d\n", time1, time2);
}
输出:
2、gmtime:获取格林威治时间
1)函数原型
struct tm *gmtime(const time_t *timep);
2)所属头文件
#include <time.h>
3)返回值
成功: 返回格林威治时间, 以struct tm形式存储
失败: NULL
struct tm { int tm_sec; /* seconds 秒*/ int tm_min; /* minutes 分*/ int tm_hour; /* hours 时*/ int tm_mday; /* day of the month */ int tm_mon; /* month */ int tm_year; /* year */ int tm_wday; /* day of the week */ int tm_yday; /* day in the year */ int tm_isdst; /* daylight saving time */ };
4)参数说明
timep: 转化的日历时间
* 案例: 获取日历时间 → 格林威治时间
#include <time.h>
#include <stdio.h>
void main()
{
time_t ctime;
struct tm *tm;
/* Get calendar time */
ctime = time(NULL);
/* Transform calendar time to standar time */
tm = gmtime(&ctime);
printf("Now is %d:%d:%d \n", tm->tm_hour, tm->tm_min, tm->tm_sec);
}
输出:
* 这里的时间怎么回事儿, 看不懂啊, 明明是下午了? 原来这并不是本地的时间, 时区不同当然有时差啦. 下面我们来获取本地时间.
3、localtime:获取本地时间
1)函数原型
struct tm *localtime(const time_t *timep);
2)所属头文件
#include <time.h>
3)返回值
成功: 返回struct tm格式存储的本地时间
失败: NULL
4)参数说明
timep: 转化的日历时间
4、asctime:时间转字符串
1)函数原型
char *asctime(const struct tm *tm);
2)所属头文件
#include <time.h>
3)返回值
成功: 返回时间转化的字符串
失败: NULL
4)参数说明
tm: 待转化的tm格式的时间
* 案例: 获取本地时间 → 显示 → 以字符串方式显示时间
#include <time.h>
#include <stdio.h>
void main()
{
time_t ctime = 0;
struct tm *tm;
char *tm_str = NULL;
/* 获取日历时间 */
ctime = time(NULL);
/*转化为本地时间 */
tm = localtime(&ctime);
printf("Localtime: %d:%d:%d\n", tm->tm_hour, tm->tm_min, tm->tm_sec);
/* 转化为字符串 */
tm_str = asctime(tm);
printf("Now time is(string): %s\n", tm_str);
}
输出:
5、gettimeofday:获取高精度时间
1)函数原型
int gettimeofday(struct timeval *tv, struct timezone *tz);
2)所属头文件
#include <sys/time.h>
3)返回值
成功: 返回高精度时间
失败: -1
4)参数说明
tv: 从1970年1月1日0时到现在经理的秒数和微妙数
tz: 一般为空.
* 案例: 获取高精度时间
#include <stdio.h>
#include <sys/time.h>
void main()
{
struct timeval tv;
gettimeofday(&tv, NULL);
printf("Sec: %d, Usec: %d\n", tv.tv_sec, tv.tv_usec);
}
输出:
* 这里还可以把秒数作为格林威治时间进行转化.
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
void main()
{
struct timeval tv;
struct tm *tm;
gettimeofday(&tv, NULL);
printf("Sec: %d, Usec: %d\n", tv.tv_sec, tv.tv_usec);
/* 转化为本地时间 */
tm = localtime(&(tv.tv_sec));
printf("Localtime: %d:%d:%d\n", tm->tm_hour, tm->tm_min, tm->tm_sec);
}
输出: