Linux时间函数编程
世界标准时间(Coordinated Universal Time):UTC为大家所熟知的格林威治标准时间(Greenwich Mean Time, GMT)。
Calender Time:日历时间,是用“从一个标准时间点(1970年1月1日0点)到此时经过的秒数”来表示时间。
1.1 获取日历时间
1.1.1 函数名 time
1.1.2 函数原形 time_t time(time_t *t);
1.1.3 函数功能 获取日历时间
1.1.4 所属头文件
1.1.5 返回值 成功:返回1970年1月1日0点至当前时间的秒数 失败:-1
1.1.6 参数说明 t:不为空的情况下保存返回值
1.2 获取格林威治时间
1.2.1 函数名 gmtime
1.2.2 函数原形 struct tm* gmtime(const time_t *timep);
1.2.3 函数功能 将参数timep所指向的日历时间转化为世界标准时间
1.2.4 所属头文件
1.2.5 返回值 成功:返回标准时间,以struct tm方式存储。 失败:返回NULL
1.2.6 参数说明 timep:待转化的日历时间
1.3 获取本地时间
1.3.1 函数名 localtime
1.3.2 函数原形 struct tm *localtime(const time_t *timep);
1.3.3 函数功能 将参数timep所指向的日历时间转化为本地时间
1.3.4 所属头文件
1.3.5 返回值 成功:返回以struct tm形式存储的本地时间 失败:NULL
1.3.6 参数说明 timep:待转化的日历时间
1.4 以字符串方式显示时间
1.4.1 函数名 asctime
1.4.2 函数原形 char *asctime(const struct tm *tm);
1.4.3 函数功能 将struct tm格式的时间转化为字符串
1.4.4 所属头文件
1.4.5 返回值 成功:字符串方式显示的时间 失败:NULL
1.4.6 参数说明 tm:待转化的tm格式的时间
1.5 获取高精度时间
1.5.1 函数名 gettimeofday
1.5.2 函数原形 int gettimeofday(struct timeval *tv, struct timezone *tz);
1.5.3 函数功能 获取高精度时间
1.5.4 所属头文件
1.5.5 返回值 成功:0 失败:-1
1.5.6 参数说明 tv:保存从1970年1月1日0点至当前经历的秒数和微秒数。 tzone:通常为NULL

总结:![]()

小实验:
#include
#include
#include
int main()
{
time_t calander_time;
struct tm *greenwich_time;
struct tm *local_time;
char *asc_time;
struct timeval hd_time;
calander_time = time(NULL);//日历时间
printf("calander time is %d!\n", calander_time);
greenwich_time = gmtime(&calander_time);//格林威治时间
printf("greenwich_time is : year->%d, month->%d, minute->%d\n", greenwich_time->tm_year, greenwich_time->tm_mon);
local_time = localtime(&calander_time); //本地时间
printf("local_time is : year->%d, month->%d, minute->%d\n", local_time->tm_year, local_time->tm_mon);
asc_time = asctime(local_time);//字符串输出时间
printf("time is %s\n", asc_time);
gettimeofday(&hd_time, NULL);//高精度时间
printf("high definition time is sec:%d usec:%d\n",hd_time.tv_sec, hd_time.tv_usec);
return 0;
}
#include
#include
int main()
{
time_t calander_time;
struct tm *greenwich_time;
struct tm *local_time;
char *asc_time;
struct timeval hd_time;
calander_time = time(NULL);//日历时间
printf("calander time is %d!\n", calander_time);
greenwich_time = gmtime(&calander_time);//格林威治时间
printf("greenwich_time is : year->%d, month->%d, minute->%d\n", greenwich_time->tm_year, greenwich_time->tm_mon);
local_time = localtime(&calander_time); //本地时间
printf("local_time is : year->%d, month->%d, minute->%d\n", local_time->tm_year, local_time->tm_mon);
asc_time = asctime(local_time);//字符串输出时间
printf("time is %s\n", asc_time);
gettimeofday(&hd_time, NULL);//高精度时间
printf("high definition time is sec:%d usec:%d\n",hd_time.tv_sec, hd_time.tv_usec);
return 0;
}

![})]at@2u$8~%z85){b1ne}t.jpg](http://download.bbs.ednchina.com/images/attachments/201503/9950190503_TIME_1425611260474.jpg)
浙公网安备 33010602011771号