【Linux C】时间转换函数

数据类型

time_t:其实就是一个long int类型

struct tm {
               int tm_sec;         /* seconds */
               int tm_min;         /* minutes */
               int tm_hour;        /* hours */
               int tm_mday;        /* day of the month */
               int tm_mon;         /* month */
               int tm_year;        /* year */
               int tm_wday;        /* day of the week */
               int tm_yday;        /* day in the year */
               int tm_isdst;       /* daylight saving time */
           };

函数说明

time_t time(time_t *t);

该函数主要是获取秒数,这个秒数是从1970-01-01 00:00:00 +0000 (UTC)开始计算的,你可以通过返回值去获取,你可以通过参数t去获取

char *asctime(const struct tm *tm);

该函数主要是将一个tm结构体转换为字符串形式的时间

char *ctime(const time_t *timep);

该函数主要是将秒数转换为一个字符串行为的时间

struct tm *localtime(const time_t *timep);

该函数主要是将秒数转换为一个tm结构体

例子介绍

下面介绍一个例子来说明上面四个函数的用法,实现秒数转时间

#include <stdio.h>
#include <time.h>


void show_tm(struct tm * t)
{
    printf("%d-%d-%d", t->tm_year+1900, t->tm_mon+1, t->tm_mday);
    printf("  ");
    printf("%d:%d:%d\n", t->tm_hour, t->tm_min, t->tm_sec);  
}

void main(void)
{
    long int curr_time = 0;
    struct tm * t;

    time(&curr_time);

    printf("time=%ld\n", curr_time);

    t = localtime(&curr_time);
    show_tm(t);

    printf("%s", ctime(&curr_time));

    printf("%s", asctime(t));
}

运行效果

这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值