两种表示法:
calendar time 对应timer_t结构
broken-down 表示法,对应struct tm结构
1,time()函数的作用是获取秒数
2,ctime()函数把秒数转为字符串
3,mktime把struct tm结构转为秒数。
mktime( ) - convert broken-down time into calendar time (ANSI)
strftime( ) - convert broken-down time into a formatted string (ANSI)
time( ) - determine the current calendar time (ANSI)
ctime( ) - convert time in seconds into a string (ANSI)
gmtime( ) - convert calendar time into UTC broken-down time (ANSI)
例子:
#include<time.h>
void clkTest(void)
{
struct timespec tp;
struct tm *ptm2;
int ret;
ret=clock_gettime(CLOCK_REALTIME,&tp);
if(0==ret)
{
printf("tp.tv_sec=%d,tp.tv_nsec=%d\n",tp.tv_sec,tp.tv_nsec);
}
ret=clock_gettime(CLOCK_MONOTONIC,&tp);
if(0==ret)
{
printf("tp.tv_sec=%d,tp.tv_nsec=%d\n",tp.tv_sec,tp.tv_nsec);
}
timer_t t1;
t1=time(&t1);
printf("%s\n",ctime(&t1));
ptm2=gmtime(&t1);
printf("asctime %s\n",asctime(ptm2));
}
void clkSet(void)
{
time_t t1;
struct tm tm1;
struct timespec tp;
tm1.tm_year=2018;
tm1.tm_mday=12;
tm1.tm_mon=5;
tm1.tm_hour=15;
tm1.tm_min=38;
tm1.tm_sec=59;
t1=mktime(&tm1);
printf("%d\n",t1);
printf("%s\n",ctime(&t1));
printf("asctime %s\n",&tm1);
tp.tv_sec=t1;
tp.tv_nsec=0;
(void)clock_settime(CLOCK_REALTIME,&tp);
}
-> clkTest
tp.tv_sec=15,tp.tv_nsec=949999962
tp.tv_sec=17,tp.tv_nsec=249999990
THU JAN 01 00:00:15 1970
asctime THU JAN 01 00:00:15 1970
value = 34 = 0x22 = '"'
-> clkSet
1357416195
SAT JAN 05 20:03:15 2013
asctime ;
value = 0 = 0x0
-> clkTest
tp.tv_sec=1357416212,tp.tv_nsec=283333322
tp.tv_sec=81,tp.tv_nsec=799999968
SAT JAN 05 20:03:32 2013
asctime SAT JAN 05 20:03:32 2013
value = 34 = 0x22 = '"'
->