time函数相关

概述

本历程都是Linux下关于时间计算函数使用,基准时间为 1970-01-01 00:00:00 +0000(UTC)
这里写图片描述
注意xx与xx_r的使用方式,涉及到可重入与不可重入函数的使用

正文

函数time(获取秒数)

函数原型

time_t time(time_t *t);

参数

参数t是把time获取的秒数存到地址处

返回值

返回时间(s)

函数ctime(由秒数获取字符串时间)

函数原型

char *ctime(const time_t *timep);
char *ctime_r(const time_t *timep, char *buf);

参数

参数timep为秒数的地址
参数buf为需要存储字符串地址

返回值

字符串地址

函数asctime(由结构体获取字符串)

函数原型

char *asctime(const struct tm *tm);
char *asctime_r(const struct tm *tm, char *buf);

参数

参数tm为需要转换的结构体地址
参数buf为需要存储字符串地址

返回值

字符串地址

函数strftime(按特定格式 输出字符串时间)

函数原型

size_t strftime(char *s, size_t max, const char *format,const struct tm *tm);

参数

参数s为存入的数组地址
参数max为存入的数组大小
参数format为需要输出的格式
参数tm为需要转换的时间结构体

返回值

函数gmtime(国际时间)

函数原型

struct tm *gmtime(const time_t *timep);
struct tm *gmtime_r(const time_t *timep, struct tm *result);

参数

参数timep为需要转换的秒数
参数result为转换后的结构体地址

返回值

转换后的结构体地址

函数localtime(本地时间)

函数原型

struct tm *localtime(const time_t *timep);
struct tm *localtime_r(const time_t *timep, struct tm *result);

参数

参数timep为需要转换的秒数
参数result为转换后的结构体地址

返回值

转换后的结构体地址

函数mktime(把具体时间转换为秒数)

函数原型

time_t mktime(struct tm *tm);

参数

参数tm为需要转换的结构体地址

返回值

转换好的秒数

测试代码

int main(void)
{
    time_t Mytime_t = 0;
    char buf[30] = {0};
    time(&Mytime_t);        /*获取当前时间的秒数,以1970-01-01 00:00:00 +0000(UTC)为基准*/
    if(Mytime_t < 0)
    {
        perror("time ");
        return -1;
    }
    printf("Mytime_t  = %ld\r\n",Mytime_t);

    ctime_r(&Mytime_t,buf);  /*把秒转换为字符串*/
    printf("ctime_r = %s\r\n",buf);

    struct tm localtm,gmtm;
    memset(&localtm,0,sizeof(localtm));
    memset(&gmtm,0,sizeof(gmtm));
    localtime_r(&Mytime_t,&localtm);/*把秒转换为结构体,当地时间*/
    gmtime_r(&Mytime_t,&gmtm);/*把秒转换为结构体,国际时间*/

    asctime_r(&localtm,buf);/*把当地时间结构体转换为字符串*/
    printf("asctime_r localtm = %s\r\n",buf);
    asctime_r(&gmtm,buf);/*把国际时间结构体转换为字符串*/
    printf("asctime_r gmtm = %s\r\n",buf);

    strftime(buf,30,"%Y * %m * %d, %H-%M-%S.",&localtm);/* 年*月*日 时-分-秒*/
    printf("strftime localtm = %s\r\n",buf);

    strftime(buf,30,"%Y * %m * %d, %H-%M-%S.",&gmtm);/* 年*月*日 时-分-秒*/
    printf("strftime gmtm = %s\r\n",buf);

    /*************************************************/
    struct tm Mymktime;
    time_t Mytime_t2 = 0;
    memset(&Mymktime,0,sizeof(Mymktime));
    Mymktime.tm_sec = 55; 
    Mymktime.tm_min = 49;
    Mymktime.tm_hour = 15;
    Mymktime.tm_mday = 30;
    Mymktime.tm_mon = 5 - 1;
    Mymktime.tm_year = 2017 - 1900;
    Mytime_t2 = mktime(&Mymktime);/*把2017/05/30 15:49:55转换为秒数*/
    printf("Mytime_t2  = %ld\r\n",Mytime_t2);
    return 0;
}

这里写图片描述

参考

参考朱友鹏Linux教程资料

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值