【Linux C】时间转换函数

来源:互联网 发布:程序员英语软件 编辑:程序博客网 时间:2024/04/30 00:16

数据类型

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