本文共 2603 字,大约阅读时间需要 8 分钟。
首先了解几个与时间相关的概念
世界标准时间:即格林威治时间; 日历时间:从1970年1月1日0点到此时经历过的秒数,是一个整数。该函数功能为获得日历时间。包含的头文件为time.h,函数运行成功则返回日历时间,失败返回-1.如果参数指针t不为NULL,则返回值会保存在t。
#include#include void main(){ time_t ctime; ctime=time(NULL); printf("time is %d\n",ctime);}
该函数功能为将日历时间timep指定的日历时间转化为世界标准时间。包含的头文件time.h,函数运行成功则返回世界标准时间,以struct tm形式存储。
#include#include void main(){ time_t ctime; ctime=time(NULL); struct tm *t; t=gmtime(&ctime); printf("the time is %d:%d:%d",t->tm_hour ,t->tm_min ,t->tm_sec );}
其中struct tm结构体为:
struct tm { int tm_sec; // seconds after the minute - [0,59] int tm_min; // minutes after the hour - [0,59] int tm_hour; // hours since midnight - [0,23] int tm_mday; // day of the month - [1,31] int tm_mon; // months since January - [0,11] int tm_year; // years since 1900 int tm_wday; // days since Sunday - [0,6] int tm_yday; // days since January 1 - [0,365] int tm_isdst; // daylight savings time flag};
该函数功能为将日历时间timep指定的日历时间转化为本地时间。包含的头文件time.h,函数运行成功则返回本地时间,以struct tm形式存储。失败返回NULL。
#include#include void main(){ time_t ctime; ctime=time(NULL); struct tm *t; t=localtime(&ctime); printf("the time is %d:%d:%d",t->tm_hour ,t->tm_min ,t->tm_sec );}
该函数功能为将struct tm格式的时间转化为字符串形式。包含的头文件为time.h,运行成功则返回字符串显示的时间
#include#include void main(){ time_t ctime; ctime=time(NULL); struct tm *t; t=localtime(&ctime); printf("the time is %d:%d:%d\n",t->tm_hour ,t->tm_min ,t->tm_sec ); char *asct=asctime(t); printf("the time is %s\n",asct);}
该函数功能为获取高精度时间,精度为微秒级。包含的头文件为<sys/time.h>
,该头文件不是c的库文件,是Linux系统的。成功返回0,失败返回-1.函数运行结束后,日历时间和微秒数会保存到参数tv中,tzone一般设置为NULL。
struct timeval{ time_t tv_sec; suseconds_t tv_usec;}
#include#include #include void main(){ time_t ctime; ctime=time(NULL); printf("the calendar time is %d\n", ctime); struct tm *t; t=gmtime(&ctime); printf("the gttime is %d:%d:%d\n", t->tm_hour , t->tm_min , t->tm_sec ); t=localtime(&ctime); printf("the localtime is %d:%d:%d\n", t->tm_hour , t->tm_min , t->tm_sec ); char *asct=asctime(t); printf("the asctime is %s", asct); struct timeval tv; gettimeofday(&tv, NULL); printf("gettimeofday sec is %d, usec is %d\n", tv.tv_sec, tv.tv_usec);}