time(),ctime()和mktime()函数使用

两种表示法:
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 = '"'
-> 
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值